package com.yc.class_attendance;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.gson.reflect.TypeToken;
import com.hwangjr.rxbus.RxBus;
import com.yc.class_attendance.adapter.Gallery_adapter;
import com.yc.class_attendance.adapter.ReGallery_adapter;
import com.yc.class_attendance.adapter.RecordAdapter;
import com.yc.class_attendance.entity.AttMeetingResutl;
import com.yc.class_attendance.entity.Attachment;
import com.yc.class_attendance.entity.AttendanceResutl;
import com.yc.class_attendance.entity.ImageResutl;
import com.yc.class_attendance.entity.MeetingResutl;
import com.yc.class_attendance.entity.PersonnelResutl;
import com.yc.class_attendance.entity.Record;
import com.yc.class_attendance.entity.RecordDao;
import com.yc.class_attendance.entity.Resutl;
import com.yc.class_attendance.entity.TempBean;
import com.yc.class_attendance.fragment.SetDiagFragment;
import com.yc.class_attendance.net.AbsAPICallback;
import com.yc.class_attendance.net.Api;
import com.yc.class_attendance.utils.DatetimeUtil;
import com.yc.class_attendance.utils.JsonListUtil;
import com.yc.class_attendance.utils.MyFileUtils;
import com.yc.class_attendance.utils.RealmHelper;
import com.yc.class_attendance.utils.SharePreferenceUtil;
import com.yc.class_attendance.utils.ThreadUtil;
import com.yc.class_attendance.utils.logger.DisplayUtil;
import com.yc.class_attendance.utils.logger.MarqueeTextView;
import com.yc.class_attendance.utils.sortClass;
import com.yc.class_attendance.wideget.SignDialog;
import com.yc.nfc.ComBean;
import com.yc.nfc.MyFunc;
import com.yc.nfc.SerialHelper;

import java.security.InvalidParameterException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;
import rx.Subscriber;

import static com.yc.class_attendance.utils.DatetimeUtil.DateStrHMS;
import static com.yc.class_attendance.utils.DatetimeUtil.getSysDate;

/**
 * 中山党校 考勤
 */
public class ReMainActivity extends BaseNewActivity implements View.OnClickListener {
    private static final String TAG = ReMainActivity.class.getSimpleName();
    private TextView tiem;
    private TextView week;
    private TextView date;
    private ImageView set;
    private TextView place;
    private TextView tvTitle;
    SurfaceView preview;
    private Camera mCamera;
    SurfaceHolder mSurfaceHolder;
    private ViewGroup mMoreLayout, mMoreLayouts;
    LinearLayout linearLayout;
    ViewGroup.LayoutParams layoutParams;
    GridView listView;
    SignDialog signDialog;
    RealmHelper realmHelper;
    //    DbHelper db;
    //BIGEN1 需要缓存的集合
    List<String> class_attemdamce = new ArrayList<>();
    List<String> BigenCard = new ArrayList<>();
    List<String> EndCard = new ArrayList<>();
    List<String> CourseId = new ArrayList<>();
    List<AttendanceResutl.CourseBean.ListBean> mListBean = new ArrayList<>();

    List<MeetingResutl> mets = new ArrayList<>();
    List<PersonnelResutl> ps = new ArrayList<>();
    MeetingResutl me;
    //End1

    TextView practical;
    int indexBigen;
    int indexEnd;
    int realized = 0;
    SoundPool soundPool1 = null;

    SoundPool q_dao_late = null;
    SoundPool q_dao_s = null;
    SoundPool q_ni_Already_dao = null;
    SoundPool q_ni_Already_tui = null;
    SoundPool q_ni_buzaibenban_q = null;
    SoundPool q_tui_late = null;
    SoundPool q_tui_s = null;
    SoundPool q_wu_ni_ke = null;
    SoundPool q_wukecheng = null;

    int sourceid = 0;
    boolean isSoundReady;
    boolean subscript;

    Gallery main_gallery;
    LinearLayout main_lin;
    ReGallery_adapter reGllery;
    Gallery_adapter gallery_adapter;
    int current_circle = 0;
    Runnable timeadv;
    int count;
    GifImageView imgview;
    List<String> li = new ArrayList<String>();
    private SharePreferenceUtil mSharePreferenceUtil;
    Timer timerImgView;
    TimerTask taskImgView;
    Bitmap bitmap;
    private RecordDao mRecordDao;

    AttendanceResutl mResult;
    RecordAdapter mAdapter;
    private final String mTimeFormat = "yyyy-MM-dd hh:mm:ss";
    String strBigenTime = "";
    String mBigenAbsenteeism;
    boolean isFirst = true;
    boolean isExecute = true;//是否执行
    ArrayList<Record> mRecordList = new ArrayList<>();
    ProgressDialog MyDialog;
    Activity myActivity;
    private SerialHelper mCom;
    private DispQueueThread DispQueue;
    private boolean validDataFlag = false;
    private byte[] RecvData = new byte[512];
    private boolean isLoading = false; //是否正在上传中
    private boolean isReStart;//是否重启
    private boolean isSkip;//无课程信息 跳转
    boolean isDoChange;

    int DST_RECT_WIDTH, DST_RECT_HEIGHT;//矩形拍照尺寸
    Point rectPictureSize = null;
    int DST_CENTER_RECT_WIDTH = 280; //单位是dip
    int DST_CENTER_RECT_HEIGHT = 280;//单位是dip
    List<Integer> mListR = new ArrayList<Integer>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        realmHelper = new RealmHelper(this);
//        db =new DbHelper(this);
        myActivity = this;
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        RxBus.get().register(this);

        mSharePreferenceUtil = MyApp.getsInstance().sharePreferenceUtil;
        mSharePreferenceUtil.setSubscript(false);
        mRecordDao = MyApp.getsInstance().getDaoSession().getRecordDao();

        mListR.add(1);
        mListR.add(2);
        mListR.add(3);

        setView();
        setTiem();
        message();
        personnel();
        SetImagView();

        //定时器
        Timer timerCard = new Timer();
        TimerTask tastCard = new TimerTask() {
            @Override
            public void run() {
                if (MyApp.getsInstance().getgiDestPort() == 1) {
                    MyApp.getsInstance().setCard("1");
                }


            }
        };
        timerCard.schedule(tastCard, 1000, 1000);
        int com =  MyApp.getsInstance().sharePreferenceUtil.getCom();
        mCom = new SerialHelper(com) {
            @Override
            protected void onDataReceived(ComBean ComRecData) {
                // TODO Auto-generated method stub
                DispQueue.AddQueue(ComRecData);
                //Log.i(STORAGE_SERVICE, "222222222222222");
            }
        };
        try {
            mCom.open();
            mCom.doSetParam();
        } catch (InvalidParameterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        DispQueue = new DispQueueThread();
        DispQueue.start();
    }


    private void setTiem() {
        tiem = getView(R.id.tiem);
        week = getView(R.id.week);
        date = getView(R.id.date);
        SetData(tiem);
        week.setText("星期" + DatetimeUtil.getWhere());
        date.setText(getSysDate("yyyy年MM月dd日"));
        new Thread(new MyThread()).start();
    }

    private void message() {
    }

    private void personnel() {
    }

    private void SetImagView() {
        MarqueeTextView autoText = getView(R.id.autoText);
        autoText.setFocusable(true);
        autoText.setFocusableInTouchMode(true);
        autoText.setText(getResources().getString(R.string.tx_welcome_Title));
        main_gallery = getView(R.id.main_gallery);
        main_lin = getView(R.id.main_lin);
        preview = getView(R.id.preview);
        mSurfaceHolder = preview.getHolder();
        mSurfaceHolder.addCallback(new SufaceListener());
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//        mSurfaceHolder.setFixedSize(1080, 1920); //设置分辨率
        mSurfaceHolder.setFixedSize(1920, 1080); //设置分辨率 640, 480
//        mSurfaceHolder.setFixedSize(176,144);
        imgview = (GifImageView) getView(R.id.imgview);
//        gallery_adapter = new Gallery_adapter(this);
//        main_gallery.setAdapter(gallery_adapter);
        initReGllery();
        setCircle();
        main_gallery.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                return false;
            }
        });


        //设置滚动图片的时候，对应小圆点的图片切换
        main_gallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                View v = main_lin.getChildAt(position);
                View cuview = main_lin.getChildAt(current_circle);

                if (v != null && cuview != null) {
                    ImageView pointView = (ImageView) v;
                    ImageView curpointView = (ImageView) cuview;
                    curpointView
                            .setBackgroundResource(R.mipmap.pink);
                    pointView
                            .setBackgroundResource(R.mipmap.red);
                    current_circle = position;
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        //
        timeadv = new Runnable() {

            @Override
            public void run() {
                //获取当前的图片是哪一张图片，图片的序号，
                count = main_gallery.getSelectedItemPosition();
                //当前滚动的图片序号大于多有的图片的数量，就跳转到第一张图片，否则就跳转到下一张图片
                if (null != li && li.size() > 1) {
                    if (count + 1 >= li.size()) {
                        count = 0;
                    } else {
                        count = count + 1;
                    }
                } else {
                    if (count + 1 >= mListR.size()) {
                        count = 0;
                    } else {
                        count = count + 1;
                    }
                }
                main_gallery.setSelection(count);
                handler.postDelayed(this, 2500);

            }
        };

        //开始定时器，1000毫秒切换一次图片5
        handler.postDelayed(timeadv, 2500);

    }


    private void setView() {
        tvTitle = (TextView) findViewById(R.id.tv_Title);
        place = getView(R.id.place);
        set = getView(R.id.set);
        set.setOnClickListener(this);
        place.setText(mSharePreferenceUtil.getClassId());
        listView = getView(R.id.listview);
        practical = getView(R.id.num);
//        loadMusic();
        practical.setText("0/0/0");
        setupViews(R.layout.layout_depar, R.layout.layout_department, R.id.layout_more, R.id.tiee, realmHelper.QueryAll(), 0);

        timer.schedule(task, 1000, 1000);

        //定时器
        Timer timerCard = new Timer();
        TimerTask tastCard = new TimerTask() {
            @Override
            public void run() {
                if (MyApp.getsInstance().getgiDestPort() == 1)
                    MyApp.getsInstance().setCard("1");


            }
        };
        timerCard.schedule(tastCard, 1000, 1000);


    }

    /**
     * 获取班级信息
     *
     * @param strFlag 时间标记
     */
    private void GetClass(final String strFlag) {
        // First 条件：A 必须有记录数据，B 必须是在新的时段内 C 在数据完整无修改之前 操作
        List<Record> mListIn = mRecordDao.queryBuilder().list();
        if (null == mListIn || mListIn.size() <= 0) {
            Log.d("ws", "mListIn=" + mListIn + "新时段 加载前检查本地 无 --考勤记录--");
        } else {
            Log.d("ws", "mListIn=" + mListIn + "新时段 加载前检查本地 有 --考勤记录--");
            //1：获取考勤规则 等数据
            getCacheData();
            //2:按照正常 算出结果 上传数据
            doCheck(true);
        }
        if(null!= mListBean){
            mListBean.clear();
            MyFileUtils.deleteFile(MyFileUtils.mListBean);
            initAdapter();
            practical.setText(0 + "/" + 0 + "/" + 0);
        }
        doAynNetGetDate(strFlag);
    }

    /**
     * 网络获取 班级信息
     *
     * @param strFlag
     */
    private void doAynNetGetDate(final String strFlag) {
        Api.getInstance().GetMeeting(new AbsAPICallback<AttendanceResutl>(this) {

            @Override
            public void onCompleted() {
            }

            @Override
            public void onNext(AttendanceResutl attendanceResutl) {
                mSharePreferenceUtil.setRestartFlag("");
                mSharePreferenceUtil.setRealized(0);
                mSharePreferenceUtil.setIndexEnd(0);
                mSharePreferenceUtil.setIndexBigen(0);
                mSharePreferenceUtil.setLoadTag(true);//开启加载 list
                mSharePreferenceUtil.setIsFlagTui(false);

                mRecordDao.deleteAll();
                realmHelper.deleteDogAll(TempBean.class);
                realmHelper.deleteDogAll(MeetingResutl.class);
                realmHelper.deleteDogAll(PersonnelResutl.class);
                realmHelper.deleteDogAll(Attachment.class);
                strBigenTime = "";
                li.clear();
                mets.clear();
                ps.clear();
                EndCard.clear();
                BigenCard.clear();
                CourseId.clear();
                class_attemdamce.clear();
                mListBean.clear();
                mSharePreferenceUtil.setIsFlagTui(false);


                if (attendanceResutl.isCode()) {

                    if (null != attendanceResutl.getCourse()) {
                        if (attendanceResutl.getCourse().size() == 0) {
                            isSkip = true;
                        }
                        mSharePreferenceUtil.setRestartFlag(strFlag);

                        mResult = attendanceResutl;
                        ThreadUtil.getInstance().submit(new Runnable() {
                            @Override
                            public void run() {
                                MyFileUtils.deleteFile(MyFileUtils.mResultPath);
                                boolean isSave = MyFileUtils.saveObject2File(mResult, MyFileUtils.mResultPath);
                                Log.d(TAG, "isSave=asyncNetLoadGetRole()" + isSave);
                            }
                        });


                        mSharePreferenceUtil.setClassId(attendanceResutl.getRoomName());
                        for (int i = 0; i < attendanceResutl.getCourse().size(); i++) {
                            BigenCard.add(attendanceResutl.getCourse().get(i).getBeginTime());
                            EndCard.add(attendanceResutl.getCourse().get(i).getEndTime());
                            CourseId.add(attendanceResutl.getCourse().get(i).getUuid());//Uuid课程ID
                            class_attemdamce.add(attendanceResutl.getCourse().get(i).getClassId());

                        }

                        mSharePreferenceUtil.setIsSameClass(attendanceResutl.getIsSameClass());
                        MyApp.getsInstance().setCourseId(CourseId);
                        MyApp.getsInstance().setBigenCard(BigenCard);
                        MyApp.getsInstance().setEndCard(EndCard);
                        MyApp.getsInstance().setClass_attemdamce(class_attemdamce);


                        for (int i = 0; i < attendanceResutl.getCourse().size(); i++) {
                            MeetingResutl meetingResutl = new MeetingResutl();
                            meetingResutl.setBegin(attendanceResutl.getCourse().get(i).getBeginTime());
                            meetingResutl.setEnd(attendanceResutl.getCourse().get(i).getEndTime());
                            meetingResutl.setUuid(attendanceResutl.getCourse().get(i).getUuid());
                            meetingResutl.setClassId(attendanceResutl.getCourse().get(i).getClassId());
                            meetingResutl.setCourseId(attendanceResutl.getCourse().get(i).getUuid());
                            meetingResutl.setClassName(attendanceResutl.getCourse().get(i).getClassName());
                            meetingResutl.setCourseName(attendanceResutl.getCourse().get(i).getCourseName());
                            meetingResutl.setMainTeacherId(attendanceResutl.getCourse().get(i).getMainTeacherId());
                            meetingResutl.setMainTeacherName(attendanceResutl.getCourse().get(i).getMainTeacherName());
                            if (null == attendanceResutl.getCourse().get(i).getExtField05()) {
                                meetingResutl.setExtField05("0");
                            } else {
                                meetingResutl.setExtField05((String) attendanceResutl.getCourse().get(i).getExtField05());
                            }

                            if (attendanceResutl.getCourse().get(i).getAttachmentlist() != null && attendanceResutl.getCourse().get(i).getAttachmentlist().size() != 0) {
                                for (int j = 0; j < attendanceResutl.getCourse().get(i).getAttachmentlist().size(); j++) {
                                    Attachment attachment = new Attachment();
                                    attachment.setCourseId(attendanceResutl.getCourse().get(i).getUuid());
                                    attachment.setClassId(attendanceResutl.getCourse().get(i).getClassId());
                                    attachment.setAttachName(attendanceResutl.getCourse().get(i).getAttachmentlist().get(j).getAttachName());
                                    attachment.setAttachUrl(mSharePreferenceUtil.getServerAddress() + attendanceResutl.getCourse().get(i).getAttachmentlist().get(j).getAttachUrl());
                                    realmHelper.addDog(attachment);


                                }
                            }

                            if (attendanceResutl.getCourse().get(i).getCheckRule() != null) {
                                meetingResutl.setBeginTime(attendanceResutl.getCourse().get(i).getBeginTime());
                                meetingResutl.setEndTime(attendanceResutl.getCourse().get(i).getEndTime());
                                meetingResutl.setCheckMode(attendanceResutl.getCourse().get(i).getCheckRule().getCheckMode());
                                meetingResutl.setInBefore(attendanceResutl.getCourse().get(i).getCheckRule().getInBefore());
                                meetingResutl.setBeLate(attendanceResutl.getCourse().get(i).getCheckRule().getBeLate());
                                meetingResutl.setNeedCheckout(attendanceResutl.getCourse().get(i).getCheckRule().getNeedCheckout());
                                meetingResutl.setAbsenteeism(attendanceResutl.getCourse().get(i).getCheckRule().getAbsenteeism());
                                meetingResutl.setOutBefore(attendanceResutl.getCourse().get(i).getCheckRule().getOutBefore());
                                meetingResutl.setLeaveEarly(attendanceResutl.getCourse().get(i).getCheckRule().getLeaveEarly());
                                meetingResutl.setOutLate(attendanceResutl.getCourse().get(i).getCheckRule().getOutLate());

                            }
                            mets.add(meetingResutl);
                            realmHelper.addDog(meetingResutl);
                        }

                        for (int i = 0; i < attendanceResutl.getCourse().size(); i++) {
                            for (int j = 0; j < attendanceResutl.getCourse().get(i).getList().size(); j++) {
                                PersonnelResutl personnelResutl = new PersonnelResutl();
                                personnelResutl.setUuid(attendanceResutl.getCourse().get(i).getUuid());
                                personnelResutl.setXm(attendanceResutl.getCourse().get(i).getList().get(j).getXm());
                                personnelResutl.setCardNo(attendanceResutl.getCourse().get(i).getList().get(j).getCardNo());
                                personnelResutl.setType(0);
                                personnelResutl.setTime("00:00:00");
                                personnelResutl.setInResult("4");
                                personnelResutl.setOutResult(null);
                                personnelResutl.setAttendResult("4");
                                personnelResutl.setLg("0");
                                personnelResutl.setClassId(attendanceResutl.getCourse().get(i).getClassId());
                                personnelResutl.setCourseId(attendanceResutl.getCourse().get(i).getUuid());//Uuid课程ID
                                personnelResutl.setWlkh(attendanceResutl.getCourse().get(i).getList().get(j).getFactoryfixId());
                                personnelResutl.setTermCode(attendanceResutl.getCourse().get(0).getScheduleAddress());
                                personnelResutl.setUseState(attendanceResutl.getCourse().get(i).getList().get(j).getUseState());
                                personnelResutl.setUserId(attendanceResutl.getCourse().get(i).getList().get(j).getTraineeId());
                                realmHelper.addDog(personnelResutl);

                                ps.add(personnelResutl);

                                Record re = new Record();
                                re.setId(null);
                                re.setWlkh(attendanceResutl.getCourse().get(i).getList().get(j).getFactoryfixId());
                                re.setClassId(attendanceResutl.getCourse().get(i).getClassId());
                                re.setCourseId(attendanceResutl.getCourse().get(i).getUuid());//Uuid课程ID
                                re.setTime(null);
                                re.setInResult("4");//签到状态(1-正常 2-迟到4-缺勤 )
                                re.setOutResult("-1");// //签退状态(1-正常  3-早退)
                                re.setAttendResult("4"); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退
                                re.setTermCode(attendanceResutl.getCourse().get(0).getScheduleAddress());//设备号
                                re.setLg("-1");//签到签退标识0-签到，1-签退  -1 缺勤
                                re.setUserId(attendanceResutl.getCourse().get(i).getList().get(j).getTraineeId());
                                re.setSatrtTime(attendanceResutl.getCourse().get(i).getBeginTime());
                                re.setEndTime(attendanceResutl.getCourse().get(i).getEndTime());
                                re.setTag("");
                                re.setIsUpload(false);
                                mRecordList.add(re);

                            }


                        }

                        //缓存处理
                        ThreadUtil.getInstance().submit(new Runnable() {
                            @Override
                            public void run() {

                                MyFileUtils.deleteFile(MyFileUtils.CourseId);
                                MyFileUtils.deleteFile(MyFileUtils.BigenCard);
                                MyFileUtils.deleteFile(MyFileUtils.EndCard);
                                MyFileUtils.deleteFile(MyFileUtils.class_attemdamce);
                                MyFileUtils.deleteFile(MyFileUtils.mets);
                                MyFileUtils.deleteFile(MyFileUtils.ps);
                                MyFileUtils.deleteFile(MyFileUtils.mListBean);

                                MyFileUtils.saveObject2File(CourseId, MyFileUtils.CourseId);
                                MyFileUtils.saveObject2File(BigenCard, MyFileUtils.BigenCard);
                                MyFileUtils.saveObject2File(EndCard, MyFileUtils.EndCard);
                                MyFileUtils.saveObject2File(class_attemdamce, MyFileUtils.class_attemdamce);

                                MyFileUtils.saveObject2File(mets, MyFileUtils.mets);
                                MyFileUtils.saveObject2File(ps, MyFileUtils.ps);


                            }
                        });
                        //
                    } else {//如果课程没有数据 1：尝试下载 会议的数据如果有跳转
                        isSkip = true;
                    }

                    //indexBigen = 0;
                    //indexEnd = 0;
                   /* if( mSharePreferenceUtil.getRestartFlag()){
                        mSharePreferenceUtil.setIndexBigen(0);
                        mSharePreferenceUtil.setIndexEnd(0);
                    }*/

                    place.setText(attendanceResutl.getRoomName());
                    setupViews(R.layout.layout_depar, R.layout.layout_department, R.id.layout_more, R.id.tiee, realmHelper.QueryAll(), 0);

                    for (int i = 0; i < realmHelper.QueryImag(CourseId.get(0), class_attemdamce.get(0)).size(); i++) {
                        Attachment attachment = ((Attachment) realmHelper.QueryImag(CourseId.get(0), class_attemdamce.get(0)).get(i));
                        li.add(attachment.getAttachUrl());
                    }

                    if (li != null) {
                        Log.d(TAG, "attachment.getAttachUrl()--" + li.size() + "" + li.get(0));
                    } else {
                        Log.d(TAG, "attachment.getAttachUrl()--size" + li.size());
                    }


                    if (li.size() != 0) {
//                        gallery_adapter.setList(li);
                        initGallery_adapter();
                        setCircle();
                    }

                }
            }

            //
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                if (e != null) {
                    Log.i(TAG, "e：" + e.getMessage());
                }


            }


        }, mSharePreferenceUtil.getEquipment(), getSysDate("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 跳转 会议App
     */
    private void doAPPChange() {

        Intent intent = new Intent(Intent.ACTION_MAIN);
        //知道要跳转应用的包名、类名
        ComponentName componentName = new ComponentName("com.yc.meeting_attendance", "com.yc.meeting_attendance.MainActivity");
        intent.setComponent(componentName);
        startActivity(intent);
        doClearDataReStart();
    }

    /**
     * 清除缓存
     */
    private void doClearDataReStart() {
        //
        mSharePreferenceUtil.setRestartFlag("");
        mSharePreferenceUtil.setRealized(0);
        mSharePreferenceUtil.setIndexEnd(0);
        mSharePreferenceUtil.setIndexBigen(0);
        mSharePreferenceUtil.setSubscript(false);
        mSharePreferenceUtil.setFig(false);
        mSharePreferenceUtil.setDataFig(false);
        mSharePreferenceUtil.setIsFlagTui(false);
        System.exit(0);

    }

    //设置滚动图片的小圆点
    private void setCircle() {
        main_lin.removeAllViews();
        for (int i = 0; i < li.size(); i++) {
            ImageView iv = new ImageView(ReMainActivity.this);
            //循环创建小圆点，判断第一个小圆点为白色的，其他的都是透明的
            if (i == 0) {
                iv.setBackgroundResource(R.mipmap.red);
            } else {
                iv.setBackgroundResource(R.mipmap.pink);
            }
            main_lin.addView(iv);
            //设置小圆点的margin值
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);  //
            lp.setMargins(5, 10, 5, 10);
            iv.setLayoutParams(lp);
        }
    }

    private void setupViews(int layout1, int layout2, int layout3, int layout4, List<MeetingResutl> list, int type) {

        mMoreLayout = getView(layout3);   //找到该容器（这里的控件为LinearLayout，转换为ViewGroup是因为ViewGroup是容器的基类）
        mMoreLayouts = getView(layout4);
        mMoreLayout.removeAllViews();
        mMoreLayouts.removeAllViews();

        /**
         * 由于文字也是动态生成，这里用数组比较多余，使用android中array文件定义资源文件，并取出(便于管理，文字和代码分开，日后要修改直接找资源数组文件便可，不用找代码)
         */

        final String[] categoriess = {"班级", "时间", "课程", "教师"};


        /**
         * 动态添加布局方法封装
         * 参数 1.父容器    2.资源文字数组  3.从第几个开始   4.行数
         */
        fillViewsOne(mMoreLayouts, categoriess, layout1);
        if (list.size() != 0) {
//            fillView(mMoreLayout, list, layout2);
            fillViews(mMoreLayout, list, layout2);
        }
//        fillViewsOne(mMoreLayouts, categories, layout1);


    }

    public void fillViews(ViewGroup layout, List<MeetingResutl> list, int lone) {
        String firstCategory = null;
        String secondCategory = null;
        String thirdCategory = null;
        for (int i = 0; i < 4; i++) {
            if (list.size() == 1) {
                if (i == 0) {
                    firstCategory = list.get(0).getClassName();
                } else if (i == 1) {
                    firstCategory = DatetimeUtil.gethour(list.get(0).getBegin()) + " - " + DatetimeUtil.gethour(list.get(0).getEnd());
                } else if (i == 2) {
                    firstCategory = list.get(0).getCourseName();
                } else if (i == 3) {
                    firstCategory = list.get(0).getMainTeacherName();
                }

            } else if (list.size() == 2) {
                if (i == 0) {

                    firstCategory = list.get(0).getClassName();
                    secondCategory = list.get(1).getClassName();
                } else if (i == 1) {
                    firstCategory = DatetimeUtil.gethour(list.get(0).getBegin()) + " - " + DatetimeUtil.gethour(list.get(0).getEnd());
                    secondCategory = DatetimeUtil.gethour(list.get(1).getBegin()) + " - " + DatetimeUtil.gethour(list.get(1).getEnd());

                } else if (i == 2) {
                    firstCategory = list.get(0).getCourseName();
                    secondCategory = list.get(1).getCourseName();

                } else if (i == 3) {
                    firstCategory = list.get(0).getMainTeacherName();
                    secondCategory = list.get(1).getMainTeacherName();
                }

            } else if (list.size() == 3) {
                if (i == 0) {
                    firstCategory = list.get(0).getClassName();
                    secondCategory = list.get(1).getClassName();
                    thirdCategory = list.get(2).getClassName();

                } else if (i == 1) {
                    firstCategory = DatetimeUtil.gethour(list.get(0).getBegin()) + " - " + DatetimeUtil.gethour(list.get(0).getEnd());
                    secondCategory = DatetimeUtil.gethour(list.get(1).getBegin()) + " - " + DatetimeUtil.gethour(list.get(1).getEnd());
                    thirdCategory = DatetimeUtil.gethour(list.get(2).getBegin()) + " - " + DatetimeUtil.gethour(list.get(2).getEnd());

                }
                if (i == 2) {
                    firstCategory = list.get(0).getCourseName();
                    secondCategory = list.get(1).getCourseName();
                    thirdCategory = list.get(2).getCourseName();

                }
                if (i == 3) {
                    firstCategory = list.get(0).getMainTeacherName();
                    secondCategory = list.get(1).getMainTeacherName();
                    thirdCategory = list.get(2).getMainTeacherName();
                }

            }
            if (CourseId.size() == 1 || mSharePreferenceUtil.getIsSameClass() == 0) {//一个班，或 班级一样（就返回 0 ，否则1）
                linearLayout = new LinearLayout(this);


                // 表格第一条线
                View.inflate(this, R.layout.layout_line_horizonal, layout);
                View.inflate(this, R.layout.layout_line_vertical, linearLayout);
                // 第一个子布局
                View.inflate(this, lone, linearLayout);
                View.inflate(this, R.layout.layout_line_vertical, linearLayout);

                // 第二个子布局
                if (i != 0) {
                    View.inflate(this, lone, linearLayout);
                    Log.d("www", i + "");
                    View.inflate(this, R.layout.layout_line_vertical, linearLayout);


                    // 第三个子布局
                    View.inflate(this, lone, linearLayout);
                    View.inflate(this, R.layout.layout_line_vertical, linearLayout);
                }


                layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layout.addView(linearLayout, layoutParams);

                // 表格最后一条线
                View.inflate(this, R.layout.layout_line_horizonal, layout);

                //根据索引getChildAt到指定的位置
                if (i != 0) {
                    final View firstView = linearLayout.getChildAt(1);
                    firstView.setTag(firstCategory);        //设置tag，便于在后面判断点击的哪一个
                    final TextView firstTextView = (TextView) firstView.findViewById(R.id.text_title);
                    firstTextView.setText(firstCategory);   //设置文字


                    final View secondView = linearLayout.getChildAt(3);
                    secondView.setTag(secondCategory);
                    final TextView secondTextView = (TextView) secondView.findViewById(R.id.text_title);
                    secondTextView.setText(secondCategory);

                    final View thirdView = linearLayout.getChildAt(5);
                    thirdView.setTag(thirdCategory);
                    final TextView thirdTextView = (TextView) thirdView.findViewById(R.id.text_title);
                    thirdTextView.setText(thirdCategory);

                } else {
                    final View firstView = linearLayout.getChildAt(1);
                    firstView.setTag(firstCategory);        //设置tag，便于在后面判断点击的哪一个
                    final TextView firstTextView = (TextView) firstView.findViewById(R.id.text_title);
                    firstTextView.setText(firstCategory);   //设置文字
                }
            } else {


                linearLayout = new LinearLayout(this);


                // 表格第一条线
                View.inflate(this, R.layout.layout_line_horizonal, layout);
                View.inflate(this, R.layout.layout_line_vertical, linearLayout);
                // 第一个子布局
                View.inflate(this, lone, linearLayout);
                View.inflate(this, R.layout.layout_line_vertical, linearLayout);

                // 第二个子布局

                View.inflate(this, lone, linearLayout);
                Log.d("www", i + "");
                View.inflate(this, R.layout.layout_line_vertical, linearLayout);


                // 第三个子布局
                View.inflate(this, lone, linearLayout);
                View.inflate(this, R.layout.layout_line_vertical, linearLayout);


                layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layout.addView(linearLayout, layoutParams);

                // 表格最后一条线
                View.inflate(this, R.layout.layout_line_horizonal, layout);

                //根据索引getChildAt到指定的位置

                final View firstView = linearLayout.getChildAt(1);
                firstView.setTag(firstCategory);        //设置tag，便于在后面判断点击的哪一个
                final TextView firstTextView = (TextView) firstView.findViewById(R.id.text_title);
                firstTextView.setText(firstCategory);   //设置文字


                final View secondView = linearLayout.getChildAt(3);
                secondView.setTag(secondCategory);
                final TextView secondTextView = (TextView) secondView.findViewById(R.id.text_title);
                secondTextView.setText(secondCategory);

                final View thirdView = linearLayout.getChildAt(5);
                thirdView.setTag(thirdCategory);
                final TextView thirdTextView = (TextView) thirdView.findViewById(R.id.text_title);
                thirdTextView.setText(thirdCategory);


                final View firstView1 = linearLayout.getChildAt(1);
                firstView1.setTag(firstCategory);        //设置tag，便于在后面判断点击的哪一个
                final TextView firstTextView1 = (TextView) firstView1.findViewById(R.id.text_title);
                firstTextView1.setText(firstCategory);   //设置文字


            }
        }

    }


    public void fillViewsOne(ViewGroup layout, String[] categories, int lone) {
        for (int i = 0; i < categories.length; i++) {
            //找到索引，便于根据索引添加图片文件和文字
            String firstCategory = categories[i];
            linearLayout = new LinearLayout(this);
            // 表格第一条线
            View.inflate(this, R.layout.layout_line_horizonal, layout);
            // 第一个子布局
            if (i == 0) {

            }
            View.inflate(this, R.layout.layout_line_vertical, linearLayout);
            View.inflate(this, lone, linearLayout);
            View.inflate(this, R.layout.layout_line_vertical, linearLayout);

            layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layout.addView(linearLayout, layoutParams);

            // 表格最后一条线
            View.inflate(this, R.layout.layout_line_horizonal, layout);

            //根据索引getChildAt到指定的位置
            final View firstView = linearLayout.getChildAt(1);
            firstView.setTag(firstCategory);        //设置tag，便于在后面判断点击的哪一个
            final TextView firstTextView = (TextView) firstView.findViewById(R.id.text_title);
            firstTextView.setText(firstCategory);   //设置文字
        }
    }


    private void doSyc(String strClassId, String strCourseUuid, String strBigenTime, String fixId, String mCurrentTime, String InResult, String OutResult, String AttendResult,
                       String Lg, String Tag) {
        Log.d(TAG, "strClassId " + strClassId + "strCourseUuid " + strCourseUuid + "fixId " + fixId + "strBigenTime " + strBigenTime);
        Record a = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(strClassId), RecordDao.Properties.CourseId.eq(strCourseUuid), RecordDao.Properties.Wlkh.eq(fixId), RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.Tag.eq("")).unique();
        if (a != null) {
            Log.d(TAG, "开始同步处理00000000");
            Log.d(TAG, "reList re" + a.toString());
            Record reb = new Record();
            reb.setId(a.getId());
            reb.setWlkh(a.getWlkh());
            reb.setClassId(a.getClassId());
            reb.setCourseId(a.getCourseId());
            reb.setTime(mCurrentTime);
            reb.setInResult(InResult);//签到状态(1-正常 2-迟到4-缺勤 )
            reb.setOutResult(OutResult);// //签退状态(1-正常  3-早退)
            reb.setAttendResult(AttendResult); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退
            reb.setTermCode(a.getTermCode());//设备号
            reb.setLg(Lg);//签到签退标识0-签到，1-签退  -1 缺勤
            reb.setUserId(a.getUserId());
            reb.setIsUpload(a.getIsUpload());
            reb.setTag(Tag);
            reb.setSatrtTime(a.getSatrtTime());
            reb.setEndTime(a.getEndTime());

            mRecordDao.update(reb);
        } else {
            Log.d(TAG, " 没有要同步的数据---");
        }
    }

    private void doSycOut(String strClassId, String strCourseUuid, String strBigenTime, String strEndTime, String fixId, String mCurrentTime, PersonnelResutl pe, String InResult, String OutResult, String AttendResult,
                          String Lg, String Tag) {
        Log.d(TAG, "strClassId " + strClassId + "strCourseUuid " + strCourseUuid + "fixId " + fixId + "strBigenTime " + strBigenTime + "strEndTime " + strEndTime + "pe" + pe.toString());
        Log.d(TAG, "同步要签退的数据--");

        List<Record> as = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(strClassId), RecordDao.Properties.CourseId.eq(strCourseUuid), RecordDao.Properties.Wlkh.eq(fixId), RecordDao.Properties.SatrtTime.eq(strBigenTime)).list();
        if (as != null && as.size() > 0) {
            for (int i = 0; i < as.size(); i++) {
                Log.d(TAG, "as-" + as.get(i).toString());
            }
        }
        //   Record a = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(strClassId), RecordDao.Properties.CourseId.eq(strCourseUuid), RecordDao.Properties.Wlkh.eq(fixId), RecordDao.Properties.SatrtTime.eq(strBigenTime)).unique();
        if (as != null && as.size() > 0) {
            Record a = as.get(0);
            if (a != null) {
                Record re = new Record();
                re.setId(null);
                re.setWlkh(fixId);
                re.setClassId(strClassId);
                re.setCourseId(strCourseUuid);
                re.setTime(mCurrentTime);
                re.setInResult(InResult);//签到状态(1-正常 2-迟到4-缺勤 )
                re.setOutResult(OutResult);// //签退状态(1-正常  3-早退)
                re.setAttendResult(AttendResult); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退
                re.setTermCode(pe.getTermCode());//设备号
                re.setLg(Lg);//签到签退标识0-签到，1-签退  -1 缺勤
                re.setUserId(a.getUserId());
                re.setIsUpload(false);
                re.setTag(Tag);
                re.setSatrtTime(strBigenTime);
                re.setEndTime(strEndTime);

                mRecordDao.insert(re);
            }
        }
    }

    /**
     * 判断是否在签  间段
     *
     * @param
     * @param currentTime
     * @param currentTime
     */
    private boolean doTimeSlotOut(String endTime, String currentTime, int leaveEarly, int outLate) {
        boolean isTrue = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            Date targetDate = sdf.parse(currentTime);//当前时间
            Date startOut = sdf.parse(endTime);
            long startLOut = startOut.getTime() / 1000 / 60 - leaveEarly;
            long endLOut = startOut.getTime() / 1000 / 60 + outLate;

            long targetL = targetDate.getTime() / 1000 / 60;

            if (startLOut < targetL && targetL < endLOut) {
                isTrue = true;
                Log.d(TAG, "doTimeSlotOut" + isTrue);
            }
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
            isTrue = false;
        }
        return isTrue;
    }

    /**
     * 判断是否在签到 有效时间时间段
     *
     * @param beginTime
     * @param currentTime
     * @param currentTime
     */
    private boolean doTimeSlotIn(String beginTime, String currentTime, int inBefore, int absenteeism) {
        boolean isTrue = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            Date targetDate = sdf.parse(currentTime);//当前时间
            Date startIn = sdf.parse(beginTime);
            long startLIn = startIn.getTime() / 1000 / 60 - inBefore;
            long endLIn = startIn.getTime() / 1000 / 60 + absenteeism;

            long targetLIn = targetDate.getTime() / 1000 / 60;

            if (startLIn < targetLIn && targetLIn < endLIn) {
                isTrue = true;
                Log.d(TAG, "doTimeSlotIn" + isTrue);
            }
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
            isTrue = false;
        }
        return isTrue;
    }

    private void UploadImage(String base64, String wlkh, String Userid) {

        Subscriber<ImageResutl> subscriber = new AbsAPICallback<ImageResutl>(this) {
            @Override
            public void onNext(ImageResutl imageResutl) {
                Log.d("TAG", "resutl:" + imageResutl.getMessage());


            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);

            }
        };

        Api.getInstance().UploadImageString(subscriber, "TrainClass", base64, wlkh, Userid);
    }

    void doShowDialog() {
        MyDialog = new ProgressDialog(this, R.style.dialog);
        MyDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        MyDialog.setCanceledOnTouchOutside(false);
        MyDialog.setMessage("上传中...");
        MyDialog.setCancelable(false);
        MyDialog.show();
    }

    private void takePicture(final String whik, final String userId) {

        if (mCamera != null) {
            isLoading = true;//拍照标记
            startDate = new Date(System.currentTimeMillis());
            startTime = startDate.getTime();
            ThreadUtil.getInstance().submit(new Runnable() {
                @Override
                public void run() {
                    mCamera.autoFocus(null);
                    mCamera.setPreviewCallback(null);
                    mCamera.takePicture(null, null, new Camera.PictureCallback() {
                        @Override
                        public void onPictureTaken(byte[] bytes, Camera camera) {
                            Date curDate = new Date(System.currentTimeMillis());
                            long time = curDate.getTime() - startTime;
                            Log.e("www1", "抓拍返回时间：" + time);
                            if (rectPictureSize == null) {
                                rectPictureSize = createCenterPictureRect(DisplayUtil.dip2px(ReMainActivity.this, DST_CENTER_RECT_WIDTH)
                                        , DisplayUtil.dip2px(ReMainActivity.this, DST_CENTER_RECT_HEIGHT));
                                DST_RECT_WIDTH = rectPictureSize.x;
                                DST_RECT_HEIGHT = rectPictureSize.y;
                            }

                            final Bitmap bitmap = BitmapFactory.decodeByteArray
                                    (bytes, 0, bytes.length);//图片
                            Matrix matrix = new Matrix();
                            matrix.setRotate(90);
                            final Bitmap Newbm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

                         /*   int x = Newbm.getWidth() / 2 - DST_RECT_WIDTH / 2;
                            int y = Newbm.getHeight() / 2 - DST_RECT_HEIGHT / 2;*/
                            int x = Newbm.getWidth() / 2 - 200;
                            int y = Newbm.getHeight() / 2 - DST_RECT_HEIGHT / 2;
                            Log.e("www1", "DST_RECT_WIDTH：" + DST_RECT_WIDTH + "DST_RECT_HEIGHT:" + DST_RECT_HEIGHT);
                            Log.e("www1", "x:" + x + "y:" + y);
                            final Bitmap rectBitmap = Bitmap.createBitmap(Newbm, x, y, DST_RECT_HEIGHT, DST_RECT_HEIGHT);
                            final Bitmap imagBitmap = zoomImg(rectBitmap, 720, 700);


                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Date curDate1 = new Date(System.currentTimeMillis());
                                    long time1 = curDate1.getTime() - startTime;
                                    Log.e("www1", "抓拍返回后压缩后 时间：" + time1);
                                    Log.e("www1", "图片显示时间：" + 400);

                                    imgview.setImageBitmap(imagBitmap);
                                    imgview.setVisibility(View.VISIBLE);
                                    timerImgView = new Timer();
                                    taskImgView = new TimerTask() {
                                        @Override
                                        public void run() {
                                            // 需要做的事:发送消息  
                                            Message message = new Message();
                                            message.what = 2;

                                            handler.sendMessage(message);
                                            //异步上传图片
                                            UploadImage(DatetimeUtil.Bitmap2StrByBase64(Newbm), whik, userId);

                                            //清除bitmap
                                            if (null != Newbm && !Newbm.isRecycled()) {
                                                Newbm.recycle();
                                            }
                                            if (null != rectBitmap && !rectBitmap.isRecycled()) {
                                                rectBitmap.recycle();
                                            }
                                            if (null != bitmap && !bitmap.isRecycled()) {
                                                bitmap.recycle();
                                            }

                                        }
                                    };
                                    timerImgView.schedule(taskImgView, 800);// 1s后执行task,经过1s再次执行

                                }
                            });

                        }
                    });
                }
            });


            main_gallery.setVisibility(View.GONE);
            main_lin.setVisibility(View.GONE);
            //快照动画显示
            try {
                GifDrawable gifDrawable = new GifDrawable(getResources(), R.drawable.camera_picture_five);
                imgview.setImageDrawable(gifDrawable);
                imgview.setVisibility(View.VISIBLE);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    public Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高   
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例   
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数   
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片   www.2cto.com
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }

    boolean am = true;
    boolean pm = true;
    boolean night = true;
    boolean Fig;
    boolean DataFig;
    boolean isFlagTui;
    boolean isFirstFlagTui;//首次开关
    String Bigen;
    String End;
    Timer timer = new Timer(true);
    TimerTask task = new TimerTask() {

        @Override
        public void run() {
            handler.sendEmptyMessage(1);
        }
    };
    String strEnd;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (isSkip) {//无课程信息 加载会议信息(变量 加载 三个时间点 )
                        Log.d("HHH", "isSkip-" + isSkip);
                        GetMeetingInfo();
                        isSkip = false;
                    }
                    Log.d("HHH", "isDoChange----" + isDoChange);
                    if (isDoChange) {//会议信息 有数据 跳转
                        doAPPChange();
                    }

                    if (DatetimeUtil.TimeCompare(getSysDate("HH:mm"), "00:00", "11:59") && am) {
                        String sReStartFlag = mSharePreferenceUtil.getRestartFlag();
                        Log.d("HHH", "sReStartFlag" + sReStartFlag);
                        if (TextUtils.isEmpty(sReStartFlag)) {
                            mSharePreferenceUtil.setIndexBigen(0);
                            mSharePreferenceUtil.setIndexEnd(0);
                        } else {

                        }
                        am = false;
                        pm = true;
                        night = true;

                        String strAm = DatetimeUtil.getSysDate("yyyy-MM-dd") + "am";//am
                        if (sReStartFlag.equals(strAm)) {//说明当天am 已经加载过了,重启进入
                            isReStart = true;
                            Log.d("HHH", "说明当天am 已经加载过了,重启进入" + strAm);
                        } else {//第一次
                            Log.d("HHH", "说明当天am ,第一次进入" + strAm);
                            GetClass(strAm);
                            indexBigen = 0;
                            indexEnd = 0;
                            mSharePreferenceUtil.setIndexBigen(indexBigen);
                            mSharePreferenceUtil.setIndexEnd(indexEnd);
                        }
                    }
                    if (DatetimeUtil.TimeCompare(getSysDate("HH:mm"), "12:00", "17:59") && pm) {
                        String sReStartFlag = mSharePreferenceUtil.getRestartFlag();
                        Log.d("HHH", "sReStartFlag" + sReStartFlag);
                        if (TextUtils.isEmpty(sReStartFlag)) {
                            mSharePreferenceUtil.setIndexBigen(0);
                            mSharePreferenceUtil.setIndexEnd(0);
                        } else {

                        }
                        am = true;
                        night = true;
                        pm = false;

                        String strPm = DatetimeUtil.getSysDate("yyyy-MM-dd") + "pm";//pm
                        if (sReStartFlag.equals(strPm)) {//说明当天am 已经加载过了,重启进入
                            isReStart = true;
                            Log.d("HHH", "说明当天pm 已经加载过了,重启进入" + strPm);
                        } else {//第一次
                            Log.d("HHH", "说明当天pm ,第一次进入" + strPm);
                            GetClass(strPm);
                            indexBigen = 0;
                            indexEnd = 0;
                            mSharePreferenceUtil.setIndexBigen(indexBigen);
                            mSharePreferenceUtil.setIndexEnd(indexEnd);
                        }
                    }
                    if (DatetimeUtil.TimeCompare(getSysDate("HH:mm"), "18:00", "23:59") && night) {
                        String sReStartFlag = mSharePreferenceUtil.getRestartFlag();
                        Log.d("HHH", "sReStartFlag" + sReStartFlag);
                        if (TextUtils.isEmpty(sReStartFlag)) {
                            mSharePreferenceUtil.setIndexBigen(0);
                            mSharePreferenceUtil.setIndexEnd(0);
                        } else {

                        }
                        am = true;
                        night = false;
                        pm = true;

                        String strNight = DatetimeUtil.getSysDate("yyyy-MM-dd") + "night";//night
                        if (sReStartFlag.equals(strNight)) {//说明当天am 已经加载过了,重启进入
                            isReStart = true;
                            Log.d("HHH", "strNight 已经加载过了,重启进入" + strNight);
                        } else {//第一次
                            Log.d("HHH", "strNight ,第一次进入" + strNight);
                            GetClass(strNight);
                            indexBigen = 0;
                            indexEnd = 0;
                            mSharePreferenceUtil.setIndexBigen(indexBigen);
                            mSharePreferenceUtil.setIndexEnd(indexEnd);
                        }

                    }

                    indexBigen = mSharePreferenceUtil.getIndexBigen();
                    indexEnd = mSharePreferenceUtil.getIndexEnd();
                    subscript = mSharePreferenceUtil.getSubscript();
                    Fig = mSharePreferenceUtil.getFig();
                    DataFig = mSharePreferenceUtil.getDataFig();


                    CourseId = MyApp.getsInstance().getCourseId();
                    BigenCard = MyApp.getsInstance().getBigenCard();
                    EndCard = MyApp.getsInstance().getEndCard();

                    //BIGEN2 获取缓存数据
                    if (isReStart) {

                        isFlagTui = mSharePreferenceUtil.getIsFlagTui();
                        Log.d("ddss", "sss1" + isFlagTui);
                        if (isFlagTui) {
                            tvTitle.setText("已签退/请假/应到:");
                        }

                        isReStart = false;
                        mResult = (AttendanceResutl) MyFileUtils.readFile2Object(MyFileUtils.mResultPath, AttendanceResutl.class);
                        if (null != mResult) {
                            Log.d("HHH", "mResult:getCourse().size--" + mResult.getCourse().size());
                        }
                        List<MeetingResutl> metsT = (List<MeetingResutl>) MyFileUtils.readFile2Object1(MyFileUtils.mets, new TypeToken<List<MeetingResutl>>() {
                        }.getType());

                        if (null == mets) {
                            mets = new ArrayList<MeetingResutl>();
                        }
                        if (null != metsT) {
                            Log.d("HHH", "metsT:" + metsT.size());
                            mets.clear();
                            mets.addAll(metsT);
                        }
                        List<PersonnelResutl> psT = (List<PersonnelResutl>) MyFileUtils.readFile2Object1(MyFileUtils.ps, new TypeToken<List<PersonnelResutl>>() {
                        }.getType());

                        if (null == ps) {
                            ps = new ArrayList<PersonnelResutl>();
                        }
                        if (null != psT) {
                            ps.clear();
                            ps.addAll(psT);
                            Log.d("HHH", "psT :" + psT.size());
                        }
                        List<String> CourseIdT = (List<String>) MyFileUtils.readFile2Object1(MyFileUtils.CourseId, new TypeToken<List<String>>() {
                        }.getType());
                        if (null == CourseId) {
                            CourseId = new ArrayList<String>();
                        }
                        if (null != CourseIdT) {
                            CourseId.clear();
                            CourseId.addAll(CourseIdT);
                        }
                        List<String> BigenCardT = (List<String>) MyFileUtils.readFile2Object1(MyFileUtils.BigenCard, new TypeToken<List<String>>() {
                        }.getType());
                        if (null == BigenCard) {
                            BigenCard = new ArrayList<String>();
                        }
                        if (null != BigenCardT) {
                            BigenCard.clear();
                            BigenCard.addAll(BigenCardT);
                        }
                        List<String> EndCardT = (List<String>) MyFileUtils.readFile2Object1(MyFileUtils.EndCard, new TypeToken<List<String>>() {
                        }.getType());
                        if (null == EndCard) {
                            EndCard = new ArrayList<String>();
                        }
                        if (null != EndCardT) {
                            EndCard.clear();
                            EndCard.addAll(EndCardT);
                        }

                        List<String> class_attemdamceT = (List<String>) MyFileUtils.readFile2Object1(MyFileUtils.class_attemdamce, new TypeToken<List<String>>() {
                        }.getType());
                        if (null == class_attemdamce) {
                            class_attemdamce = new ArrayList<String>();
                        }
                        if (null != class_attemdamceT) {
                            class_attemdamce.clear();
                            class_attemdamce.addAll(class_attemdamceT);
                        }

                        MyApp.getsInstance().setCourseId(CourseId);
                        MyApp.getsInstance().setBigenCard(BigenCard);
                        MyApp.getsInstance().setEndCard(EndCard);
                        MyApp.getsInstance().setClass_attemdamce(class_attemdamce);


                        List<TempBean> mlistB = realmHelper.queryAllTempBean();
                        if (mlistB != null && mlistB.size() > 0) {
                            Log.d("FFF", "mlistB-总数：" + mlistB.size());

                        }

                        List<AttendanceResutl.CourseBean.ListBean> mlistA = (List<AttendanceResutl.CourseBean.ListBean>) MyFileUtils.readFile2Object1(MyFileUtils.mListBean, new TypeToken<List<AttendanceResutl.CourseBean.ListBean>>() {
                        }.getType());

                        if (null != mlistA && null != mlistB) {
                            //TODO 重启对原始数据 更新同步（断电重启的记录还原）
                            int mlistSizeA = mlistA.size();
                            int mlistSizeB = mlistB.size();
                            for (int i = 0; i < mlistSizeB; i++) {
                                TempBean b = mlistB.get(i);
                                for (int j = 0; j < mlistSizeA; j++) {
                                    if (mlistA.get(j).getFactoryfixId().equals(b.getFactoryfixId())) {
                                        mlistA.get(j).setmCurrenTime(b.getmCurrenTime());
                                        mlistA.get(j).setCardNo(b.getCardNo());
                                        mlistA.get(j).setUseState(b.getUseState());
                                        mlistA.get(j).setClassId(b.getClassId());
                                        mlistA.get(j).setType(b.getType());
                                        mlistA.get(j).setTime(b.getTime());
                                        mlistA.get(j).setXm(b.getXm());
                                        mlistA.get(j).setTraineeId(b.getTraineeId());
                                        mlistA.get(j).setIsLeave(b.getIsLeave());
                                        break;
                                    }
                                }

                            }
                        }
                        if (null != mlistA && mlistA.size() > 0) {
                            mListBean.addAll(mlistA);
                            sortClass sort = new sortClass();
                            Collections.sort(mListBean, sort);
                            initAdapter();

                            String mExtField05 = "";
                            if (null != me) {
                                mExtField05 = me.getExtField05();
                            }

                            practical.setText(mSharePreferenceUtil.getRealized() + "/" + mExtField05 + "/" + mListBean.size());
                        }

                        //设置课程列表信息
                        if (mets.size() != 0) {
                            setupViews(R.layout.layout_depar, R.layout.layout_department, R.id.layout_more, R.id.tiee, mets, 0);
                        }


                        List<String> mli = (List<String>) MyFileUtils.readFile2Object1(MyFileUtils.mListAttachUrl, new TypeToken<List<String>>() {
                        }.getType());
                        if (mli != null && mli.size() > 0) {
                            Log.e(TAG, "重启-mli-ArrURl-" + mli.get(0) + "");
                            if (li != null && li.size() > 0) {
                                li.clear();
                            }
                            li.addAll(mli);
//                            gallery_adapter.setList(li);
                            initGallery_adapter();
                            setCircle();
                        }


                        Log.e("www", "CourseId:" + CourseId.size() + "BigenCard:" + BigenCard.size() + "EndCard:" + EndCard.size() + "class_attendamce:" + class_attemdamce.size());

                    }

                    //END2
                    Log.e("www", "BigenCard.size() " + BigenCard.size() + "EndCard.size()" + EndCard.size() + "indexdEnd" + indexEnd + "indexBigen" + indexBigen);
                    if (BigenCard.size() != 0 && indexBigen < BigenCard.size() && indexEnd < EndCard.size()) {
                        if (indexBigen >= BigenCard.size() || indexEnd >= EndCard.size()) {
                            indexBigen = BigenCard.size() - 1;
                            indexEnd = EndCard.size() - 1;
                        }
                        if (mets.size() == 0) {
                            return;
                        }

                        me = mets.get(indexBigen);
                        Bigen = DatetimeUtil.getDateTimeFromMillisecond(
                                DatetimeUtil.TimeStrToSecond(BigenCard.get(indexBigen)) - 1000 * 60 * me.getInBefore());

                        mBigenAbsenteeism = DatetimeUtil.getDateTimeFromMillisecond(
                                DatetimeUtil.TimeStrToSecond(BigenCard.get(indexBigen)) + 1000 * 60 * me.getAbsenteeism());
                        if (me.getNeedCheckout() == 1) {//开启签退
                            End = DatetimeUtil.getDateTimeFromMillisecond(
                                    DatetimeUtil.TimeStrToSecond(EndCard.get(indexEnd)) + 1000 * 60 * me.getOutLate());
                        } else {
                            End = DatetimeUtil.getDateTimeFromMillisecond(
                                    DatetimeUtil.TimeStrToSecond(EndCard.get(indexEnd)));
                        }

                        Log.d("TAG", "开始时间：" + Bigen);
                        Log.d("TAG", "结束时间：" + End);
                        Log.d("TAG", "延迟缺勤时间：" + mBigenAbsenteeism);
                        Log.d("TAG", "indexBigen：" + indexBigen);
                        Log.d("TAG", "indexEnd：" + indexEnd);
                        Log.d("TAG", "subscript：" + subscript);
                        Log.d("TAG", "TimeCompare：" + DatetimeUtil.TimeCompare(getSysDate("HH:mm"), DatetimeUtil.gethour(Bigen), DatetimeUtil.gethour(End)));
                        //
                        strEnd = DatetimeUtil.getDateTimeFromMillisecond(
                                DatetimeUtil.TimeStrToSecond(EndCard.get(indexEnd)) + 1000 * 60 * me.getOutLate() + 1000 * 60 * 1);
                        if (DatetimeUtil.TimeCompareEnd(getSysDate("HH:mm"), DatetimeUtil.gethour(strEnd))) {
                            Log.d("TAG", "结束时间：" + strEnd + "结果：--" + DatetimeUtil.TimeCompareEnd(getSysDate("HH:mm"), DatetimeUtil.gethour(strEnd)));
                            List<MeetingResutl> mlist = new ArrayList<>();
                            setupViews(R.layout.layout_depar, R.layout.layout_department, R.id.layout_more, R.id.tiee, mlist, 0);
                            return;
                        }

                        //


                        Log.d("TAG", "starEnd-+2" + strEnd);
                        Log.d("TAG", "res1-" + !DatetimeUtil.TimeCompare(getSysDate("HH:mm"), DatetimeUtil.gethour(Bigen), DatetimeUtil.gethour(End)));
                        Log.d("TAG", "res2-" + DatetimeUtil.TimeCompareEnd(getSysDate("HH:mm"), DatetimeUtil.gethour(strEnd)));
                        isFlagTui = mSharePreferenceUtil.getIsFlagTui();
                        Log.d("TAG", "isFlagTui;" + isFlagTui);
                        //签退时区 更新UI
                        String BigenOut = DatetimeUtil.getDateTimeFromMillisecond(DatetimeUtil.TimeStrToSecond(EndCard.get(indexBigen)) - 1000 * 60 * me.getOutBefore());// 签退提前分钟
                        String EndOut = DatetimeUtil.getDateTimeFromMillisecond(
                                DatetimeUtil.TimeStrToSecond(EndCard.get(indexEnd)) + 1000 * 60 * me.getOutLate());// me.getOutLate()签退延迟分钟
                        boolean isArarTimeOut = DatetimeUtil.TimeCompare(DatetimeUtil.getSysDate("HH:mm"), DatetimeUtil.gethour(BigenOut), DatetimeUtil.gethour(EndOut));

                        Log.d("TAG", "开始签退时间：" + isArarTimeOut);
                        //
                        if (DatetimeUtil.TimeCompare(getSysDate("HH:mm"), DatetimeUtil.gethour(Bigen), DatetimeUtil.gethour(End)) && (!subscript)) {
                            tvTitle.setText("已实到/请假/应到:");
                            isFlagTui = false;

                            mSharePreferenceUtil.setSubscript(true);
                            mSharePreferenceUtil.setIndexBigen(indexBigen);

                            Log.d("HHH", "开始时间： 在时间签到区域内--indexBigen 第" + indexBigen + " 区域");
                            //
                            int mRecordSize = mRecordList.size();
                            Log.d("HHH", "mRecordSize--" + mRecordSize);
                            if (mRecordList != null && mRecordSize > 0) {// 构造表
                                String strBigenTime = BigenCard.get(indexBigen);
                                String strEndTime = EndCard.get(indexBigen);
                                String mCourseId = CourseId.get(indexBigen);
                                MeetingResutl me1 = mets.get(indexBigen);

                                //如果表 数据 存在不操作

                                List<Record> mListIn = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(me1.getClassId()), RecordDao.Properties.CourseId.eq(mCourseId),
                                        RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.EndTime.eq(strEndTime)
                                ).list();

                                if (mListIn != null && mListIn.size() > 0) {
                                    Log.d("HHH", "有当前表数据--");

                                } else {
                                    Log.d("HHH", "无表表数据-创建表-");
                                    for (int i = 0; i < mRecordSize; i++) {
                                        mRecordDao.insert(mRecordList.get(i));
                                    }
                                }

                            }


                            //s
                            Log.d("HHH", "无表表数据-创建表-mResult" + mResult.getCourse().size());
                            if (mResult.getCourse().size() == 0) {
                                mResult = (AttendanceResutl) MyFileUtils.readFile2Object(MyFileUtils.mResultPath, AttendanceResutl.class);
                            }
                            if (mResult != null && mResult.getCourse() != null) {
                                int mSize = mResult.getCourse().size();
                                if (mSize <= 0) {
                                    return;
                                }


                                //标记添加 一次 除非 更新时间区域 再次添加
                                if (mSharePreferenceUtil.getLoadTag()) {//默认 true
                                    if (!TextUtils.isEmpty(strBigenTime) && strBigenTime.equals(BigenCard.get(indexEnd))) {//相同课程
                                        ++indexEnd;
                                        ++indexBigen;
                                        mSharePreferenceUtil.setIndexEnd(indexEnd);
                                        mSharePreferenceUtil.setIndexBigen(indexBigen);
                                        mSharePreferenceUtil.setIsFlagTui(false);
                                        Log.d("HHH", "开始时间： 在时间区域内--indexBigen 第" + indexBigen + " 区域" + "同strBigenTime" + strBigenTime);

                                    }
                                    if (indexEnd >= BigenCard.size()) {
                                        return;

                                    }
                                    strBigenTime = BigenCard.get(indexEnd);

                                    Log.d("HHH", "开始时间 strBigenTime：" + strBigenTime);
                                    for (int i = 0; i < mSize; i++) {
                                        AttendanceResutl.CourseBean cBean = mResult.getCourse().get(i);
                                        if (strBigenTime.equals(cBean.getBeginTime())) {
                                            List<AttendanceResutl.CourseBean.ListBean> list = cBean.getList();
                                            mListBean.addAll(list);
                                            mSharePreferenceUtil.setLoadTag(false);

                                            realmHelper.deleteDogAll(TempBean.class);
                                            MyFileUtils.deleteFile(MyFileUtils.mListBean);
                                            boolean isSave = MyFileUtils.saveObject2File(mListBean, MyFileUtils.mListBean);
                                            Log.d(TAG, "默认保存-mListBean-" + isSave);
                                            break;
                                        }
                                    }


                               /*     ThreadUtil.getInstance().submit(new Runnable() {
                                        @Override
                                        public void run() {
                                            realmHelper.deleteDogAll(TempBean.class);
                                            MyFileUtils.deleteFile(MyFileUtils.mListBean);
                                            mListBean.get(0).setmCurrenTime(Bigen);
                                            boolean isSave = MyFileUtils.saveObject2File(mListBean, MyFileUtils.mListBean);
                                            Log.d(TAG, "默认保存-mListBean-" + isSave);
                                        }
                                    });*/
                                }
                            }

                            initAdapter();
                            //

                            li.clear();
                            for (int i = 0; i < realmHelper.QueryImag(CourseId.get(indexBigen), class_attemdamce.get(indexBigen)).size(); i++) {
                                Attachment attachment = ((Attachment) realmHelper.QueryImag(CourseId.get(indexBigen), class_attemdamce.get(indexBigen)).get(i));
                                li.add(attachment.getAttachUrl());
                            }
                            if (li.size() != 0) {
//                                gallery_adapter.setList(li);
                                initGallery_adapter();
                                main_gallery.setAdapter(gallery_adapter);
                                setCircle();
                                ThreadUtil.getInstance().submit(new Runnable() {
                                    @Override
                                    public void run() {
                                        MyFileUtils.deleteFile(MyFileUtils.mListAttachUrl);
                                        boolean isSave = MyFileUtils.saveObject2File(li, MyFileUtils.mListAttachUrl);
                                        Log.d(TAG, "默认保存课程图片URL保存--" + isSave);
                                    }
                                });

                            }
                            Log.d("TAG", "getIsSameClass" + mSharePreferenceUtil.getIsSameClass());


                            practical.setText(mSharePreferenceUtil.getRealized() + "/" + me.getExtField05() + "/" + mListBean.size());

                            listView.setVisibility(View.VISIBLE);


                        } else if (DatetimeUtil.TimeCompare(DatetimeUtil.getSysDate("HH:mm"), DatetimeUtil.gethour(End), DatetimeUtil.gethour(BigenOut))) {//大于签到 小于签退时间内 记录迟到
                            Log.d("HHH", "大于签到 小于签退时间内 记录迟到---");

                        } else if (isArarTimeOut && me.getNeedCheckout() == 1 && !isFirstFlagTui) {//签退时间
                            Log.d("HHH", "签退时间----");
                            Log.d("HHH", "已签退/请假/应到:");
                            isFirstFlagTui = true;
                            isFlagTui = true;
                            mSharePreferenceUtil.setIsFlagTui(true);
                            tvTitle.setText("已签退/请假/应到:");
                            realized = 0;
                            mSharePreferenceUtil.setRealized(0);
                            practical.setText(mSharePreferenceUtil.getRealized() + "/" + me.getExtField05() + "/" + mListBean.size() + "");
                        }

                        if (getSysDate("yyyy-MM-dd HH:mm:ss").equals(DatetimeUtil.getDateTimeFromMillisecond(
                                DatetimeUtil.TimeStrToSecond(End)))) {//
                            mSharePreferenceUtil.setSubscript(false);
                            {//按节次上传  刷卡 处理数据 节次和半天的业务，仅负责上传数据
                                Log.d(TAG, "自动开始准备上传-");
                                //
                                doCheck(false);

                            }
                            practical.setText(0 + "/" + 0 + "/" + 0);
                            realized = 0;
                            mSharePreferenceUtil.setRealized(0);
                            isFirstFlagTui = false;
                            indexEnd++;
                            indexBigen++;
                            mSharePreferenceUtil.setIndexEnd(indexEnd);
                            mSharePreferenceUtil.setIndexBigen(indexBigen);

                            mListBean.clear();//清除缓存
                            mSharePreferenceUtil.setLoadTag(true);//开启加载 list
//                            mSharePreferenceUtil.setIsFlagTui(false);
                            listView.setVisibility(View.GONE);
                            initAdapter();
                            //更新展示区
                            li.clear();
                            main_lin.removeAllViews();
                            if (null != gallery_adapter) {
                                gallery_adapter.notifyDataSetChanged();
                            }
                            isExecute = true;

                        }
                        if (me.getNeedCheckout() == 0 && getSysDate("yyyy-MM-dd HH:mm:ss").equals(DatetimeUtil.getDateTimeFromMillisecond(
                                DatetimeUtil.TimeStrToSecond(mBigenAbsenteeism)))) {// 无签退时：提前上传 不能更改否则上传数据不准确
                            Log.d(TAG, "提前时间开始准备上传-时间：" + mBigenAbsenteeism);
                            doCheck(true);
                        }
                        if (mSharePreferenceUtil.getIsManualUpload()) {//手动上传
                            mSharePreferenceUtil.setIsManualUpload(false);
                            mSharePreferenceUtil.setSubscript(false);
                            {//按节次上传  刷卡 处理数据 节次和半天的业务，仅负责上传数据
                                Log.d(TAG, "按节次开始准备上传-");
                                //
                                doCheck(false);
                                signDialog = SignDialog.show(ReMainActivity.this, "上传成功！", "");

                                timerImgView = new Timer();
                                taskImgView = new TimerTask() {
                                    @Override
                                    public void run() {
                                        Message message = new Message();
                                        message.what = 5;
                                        handler.sendMessage(message);
                                    }
                                };
                                timerImgView.schedule(taskImgView, 800);
                            }
                            practical.setText(0 + "/" + 0 + "/" + 0);
                            realized = 0;
                            isFirstFlagTui = false;
                            mSharePreferenceUtil.setRealized(0);
                            indexEnd++;
                            indexBigen++;
                            mSharePreferenceUtil.setIndexEnd(indexEnd);
                            mSharePreferenceUtil.setIndexBigen(indexBigen);

                            mListBean.clear();//清除缓存
                            mSharePreferenceUtil.setLoadTag(true);//开启加载 list
                            mSharePreferenceUtil.setIsFlagTui(false);
                            listView.setVisibility(View.GONE);
                            initAdapter();
                            //更新展示区
                            li.clear();
                            main_lin.removeAllViews();
                            if (null != gallery_adapter) {
                                gallery_adapter.notifyDataSetChanged();
                            }

                            isExecute = true;
                        }


//                        if (DatetimeUtil.getSysDate("yyyy-MM-dd HH:mm:ss").equals(End) && (!Fig)) {
//
//
//
//                        }

//                        if (DatetimeUtil.TimeCompare(DatetimeUtil.getSysDate("HH:mm"), DatetimeUtil.gethour(End), DatetimeUtil.gethour(DatetimeUtil.getDateTimeFromMillisecond(
//                                DatetimeUtil.TimeStrToSecond(End) + 1000 * 60 * 3))) && (!Fig)) {
//                            UploadCheck(DataFig);
//                            mSharePreferenceUtil.setSubscript(false);
//                            practical.setText(0 + "/" + 0);
//                            mSharePreferenceUtil.setRealized(0);
////                        mSharePreferenceUtil.setIndexEnd(indexEnd);
//                            Log.d("TAG", "3分钟上传");
//                        }
                        {

                            //不当前 时区内 且 在 当前课程结束后 2分钟后 清除缓存 ，上传遗留的记录
                            if (TextUtils.isEmpty(strEnd)) {
                                return;
                            }
                            if (DatetimeUtil.TimeCompareEnd(getSysDate("HH:mm"), DatetimeUtil.gethour(strEnd)) && isExecute) {
                                Log.d(TAG, "1不在时区内--清除缓存--");
                                mSharePreferenceUtil.setIsFlagTui(false);
                                mListBean.clear();
                                isFirstFlagTui = false;
                                initAdapter();
                                practical.setText(mSharePreferenceUtil.getRealized() + "/" + me.getExtField05() + "/" + mListBean.size() + "");
                                ThreadUtil.getInstance().submit(new Runnable() {
                                    @Override
                                    public void run() {

                                        realmHelper.deleteDogAll(TempBean.class);
                                        MyFileUtils.deleteFile(MyFileUtils.mListBean);
                                        MyFileUtils.deleteFile(MyFileUtils.mListAttachUrl);

                                        // 查询是否未上传过的数据
                                        List<Record> mListIn = mRecordDao.queryBuilder().where(RecordDao.Properties.IsUpload.eq(false)).list();
                                        if (mListIn != null && mListIn.size() > 0) {
                                            Log.d(TAG, "1当前课程结束" + strEnd + " + 2分钟后 清除缓存 ，查上传遗留的记录 有需要上传的数据..." + mListIn.size());
                                            String json = JSON.toJSONString(mListIn);
                                            Log.d(TAG, "listIn:" + mListIn.size());
                                            Log.d(TAG, "jsonIn:" + json);
                                            UpLoadJSON(json, false);
                                        } else {
                                            Log.d(TAG, "1当前课程结束后 2分钟后 清除缓存 ，查上传遗留的记录 无需要上传的数据...");
                                        }
                                        isExecute = false;
                                    }
                                });

                            }

                        }
                    } else {
                        List<MeetingResutl> mlist = new ArrayList<>();

                        //清除重启标记
//                        mSharePreferenceUtil.setRestartFlag("");
                        doDisEnableView();

                        Log.d("TAG", "不在时间--strEnd" + strEnd);
                        //不当前 时区内 且 在 当前课程结束后 2分钟后 清除缓存 ，上传遗留的记录
                        if (TextUtils.isEmpty(strEnd)) {
                            return;
                        }
                        if (DatetimeUtil.TimeCompareEnd(getSysDate("HH:mm"), DatetimeUtil.gethour(strEnd))) {
                            ThreadUtil.getInstance().submit(new Runnable() {
                                @Override
                                public void run() {
                                    Log.d(TAG, "2不在时区内--清除缓存--");
                                    isFirstFlagTui = false;
                                    realmHelper.deleteDogAll(TempBean.class);
                                    MyFileUtils.deleteFile(MyFileUtils.mListBean);
                                    MyFileUtils.deleteFile(MyFileUtils.mListAttachUrl);
                                    mSharePreferenceUtil.setIsFlagTui(false);
                                    // 查询是否未上传过的数据
                                    List<Record> mListIn = mRecordDao.queryBuilder().where(RecordDao.Properties.IsUpload.eq(false)).list();
                                    if (mListIn != null && mListIn.size() > 0) {
                                        Log.d(TAG, "2当前课程结束" + strEnd + " + 2分钟后 清除缓存 ，查上传遗留的记录 有需要上传的数据..." + mListIn.size());
                                        String json = JSON.toJSONString(mListIn);
                                        Log.d(TAG, "listIn:" + mListIn.size());
                                        Log.d(TAG, "jsonIn:" + json);
                                        UpLoadJSON(json, false);
                                    } else {
                                        Log.d(TAG, "2当前课程结束后 2分钟后 清除缓存 ，查上传遗留的记录 无需要上传的数据...");
                                    }
                                    strEnd = "";
                                }
                            });

                        }
                    }


                    break;

                case 2:
                    Log.d(TAG, " 接受 Message message===2");
                    Date curDate = new Date(System.currentTimeMillis());
                    long time = curDate.getTime() - startTime;
                    Log.e("www", "接受 延迟后 Message 处理时间：" + time);
                    isLoading = false;
                    cardId = "";
                    bitmap = null;
                    imgview.setImageBitmap(null);
                    main_gallery.setVisibility(View.VISIBLE);
                    main_lin.setVisibility(View.VISIBLE);
                    imgview.setVisibility(View.GONE);
                    if (timerImgView != null) {
                        taskImgView.cancel();
                    }
                    if (timer != null) {
                        task.cancel();
                    }

                    if (MyDialog != null) {
                        MyDialog.dismiss();
                    }
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    if (task != null) {
                        task.cancel();
                        task = null;
                    }

                    timer = new Timer();
                    task = new TimerTask() {
                        @Override
                        public void run() {
                            // 需要做的事:发送消息  
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                    };
                    timer.schedule(task, 1000, 1000);// 1s后执行task,经过1s再次执行

                    break;
                case 3:
                    SetData(tiem);
                    break;
                case 4:

                    break;
                case 5:
                    Log.d("TAG", "手动上传Success--");
                    if (signDialog != null && signDialog.isShowing()) {
                        signDialog.dismiss();
                        signDialog = null;
                    }
                    if (timerImgView != null) {
                        taskImgView.cancel();
                    }

                    break;
            }
        }
    };

    private void doCheck(final boolean isAbUpload) {
        if (indexBigen >= BigenCard.size() || indexEnd >= EndCard.size()) {
            return;
        }

        String strBigenTime = BigenCard.get(indexBigen);
        String strEndTime = EndCard.get(indexBigen);
        String mCourseId = CourseId.get(indexBigen);

        MeetingResutl me = mets.get(indexBigen);
        String strCourseUuid = me.getCourseId();
        String strClassId = me.getClassId();

      /*  Query queryIn = mRecordDao.queryBuilder().where(RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.Tag.eq("in")).build();
        List<Record> mListIn = queryIn.list();
        if (mListIn == null || mListIn.size() == 0) {
            Log.d(TAG, "没有签到数据--");
            return;
        }
        if (me.getNeedCheckout() == 0) { //1：未开启签退
            String json = JSON.toJSONString(mListIn);
            Log.d(TAG, "上传json 未开启签退 ");
            Log.d(TAG, "listIn:" + mListIn.size());
            Log.d(TAG, "jsonIn:" + json);

        } else */
        // 获取当前 list
        if (mResult == null) {
            Log.d("www", "mResult:" + "null");
            return;
        } else {
            Log.d("www", "mResult:" + "不为null");
        }
        int mSize = mResult.getCourse().size();
        List<AttendanceResutl.CourseBean.ListBean> mList = new ArrayList<>();
        for (int i = 0; i < mSize; i++) {
            AttendanceResutl.CourseBean cBean = mResult.getCourse().get(i);
            if (strBigenTime.equals(cBean.getBeginTime())) {
                List<AttendanceResutl.CourseBean.ListBean> list = cBean.getList();
                mList.addAll(list);
                break;
            }
        }
        ArrayList<String> UuIds = new ArrayList<>();
        // 目前有不同班级的
        //特殊情况 同班级 且 半天考勤  //1:有可能2门 班级 一样 做同步处理

        if (mSharePreferenceUtil.getIsSameClass() == 0 && me.getCheckMode() == 2) {// IsSameClass =0同班级 && CheckMode2 半天
            if (mets.size() == 3 && BigenCard.size() == 3) {//先判断课程 最多3个
                UuIds.add(CourseId.get(0));
                UuIds.add(CourseId.get(1));
                UuIds.add(CourseId.get(2));
            } else if (mets.size() == 2 && BigenCard.size() == 2) { //2个课程
                UuIds.add(CourseId.get(0));
                UuIds.add(CourseId.get(1));
            }
        } else if (mSharePreferenceUtil.getIsSameClass() == 1 && me.getCheckMode() == 2) {//不同班级 && CheckMode2 半天
            if (mets.size() == 3 && BigenCard.size() == 3) {//先判断课程 最多3个
                if (mets.get(0).getClassId().equals(mets.get(1).getClassId())) {
                    UuIds.add(CourseId.get(0));
                    UuIds.add(CourseId.get(1));
                }
                if (mets.get(0).getClassId().equals(mets.get(2).getClassId())) {
                    UuIds.add(CourseId.get(0));
                    UuIds.add(CourseId.get(2));
                }
                if (mets.get(1).getClassId().equals(mets.get(2).getClassId())) {
                    UuIds.add(CourseId.get(1));
                    UuIds.add(CourseId.get(2));
                }
            }

        }

        //
        Log.d(TAG, "按节次开始准备上传-111");
        if (me.getNeedCheckout() == 0) {//仅有 签到业务
            Log.d(TAG, "仅有 签到业务");
            Log.d(TAG, "mCourseId=" + mCourseId);
            List<Record> mListIn;
            if (me.getCheckMode() == 2) {
                Log.d(TAG, "无签退模式：同一班级，不同课程的，同步数据");
                mListIn = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(me.getClassId()),
                        RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.EndTime.eq(strEndTime)
                ).list();
            } else {
                mListIn = mRecordDao.queryBuilder().where(RecordDao.Properties.CourseId.eq(mCourseId), RecordDao.Properties.ClassId.eq(me.getClassId()),
                        RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.EndTime.eq(strEndTime)
                ).list();
            }

            Log.d(TAG, "按节次开始准备上传- me.getNeedCheckout()==0 mListIn.size()=" + mListIn.size());
            if (mListIn != null && mListIn.size() > 0) {
                String json = JSON.toJSONString(mListIn);
                Log.d(TAG, "listIn:" + mListIn.size());
                Log.d(TAG, "jsonIn:" + json);
                UpLoadJSON(json, isAbUpload);
            }
        } else {//开启签退
            Log.d(TAG, "开启签退");
            // 签退业务处理
            // 1：有签到，签退 记录，   更新 签退  attendResult ;
            // 2: 有签到 ，无签退记录， 更新签到的结果数据 更新   attendResult =4;   lg=0-签到
            //3：无签到，无签退，lg -1  attendResult 4  Time = null

            int mlSize = mList.size();
            if (mList != null && mList.size() > 0)

                if (UuIds != null && UuIds.size() > 0) {//半天有同班数据
                    for (int u = 0; u < UuIds.size(); u++) {
                        for (int i = 0; i < mlSize; i++) {
                            String fixId = mList.get(i).getFactoryfixId();
                            if (mList.get(i).getUseState() == 0) {//无效数据
                                Log.d(TAG, "无效数据 fixId=" + mList.get(i).getFactoryfixId());
                                continue;
                            }
                            //3：无签到，无签退，lg -1  attendResult 4  Time = null
                            Record a = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(strClassId), RecordDao.Properties.CourseId.eq(UuIds.get(u)), RecordDao.Properties.Wlkh.eq(fixId), RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.Tag.eq("in"), RecordDao.Properties.Time.isNotNull()).unique();
                            Record b = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(strClassId), RecordDao.Properties.CourseId.eq(UuIds.get(u)), RecordDao.Properties.Wlkh.eq(fixId), RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.Tag.eq("out"), RecordDao.Properties.Time.isNotNull()).unique();
                            if (a == null && b == null) {

                                Log.d(TAG, "3：无签到，无签退，lg -1  attendResult 4  Time = null"); //更新默认记录
                                Record mR = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(strClassId), RecordDao.Properties.CourseId.eq(strCourseUuid), RecordDao.Properties.Wlkh.eq(fixId), RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.Time.isNull()).unique();
                                if (mR == null) {
                                    continue;
                                }
                                Record re = new Record();
                                re.setId(mR.getId());
                                re.setWlkh(mR.getWlkh());
                                re.setClassId(mR.getClassId());
                                re.setCourseId(mR.getCourseId());
                                re.setTime(null);
                                re.setInResult("4");//签到状态(1-正常 2-迟到4-缺勤 )
                                re.setOutResult("-1");// //签退状态(1-正常  3-早退)
                                re.setAttendResult("4"); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退
                                re.setTermCode(mR.getTermCode());//设备号
                                re.setLg("-1");//签到签退标识0-签到，1-签退  -1 缺勤
                                re.setUserId(mR.getUserId());
                                re.setIsUpload(mR.getIsUpload());
                                re.setTag(mR.getTag());
                                re.setSatrtTime(mR.getSatrtTime());
                                re.setEndTime(mR.getEndTime());

                                mRecordDao.update(re);

                            } else if (a != null && b == null) {//2: 有签到 ，无签退记录， 更新签到的结果数据 更新   attendResult =4;   lg=0-签到
                                Log.d(TAG, "2: 有签到 ，无签退记录， 更新签到的结果数据 更新   attendResult =4;   lg= 0 签到");//更新签到记录
                                Record re = new Record();
                                re.setId(a.getId());
                                re.setWlkh(a.getWlkh());
                                re.setClassId(a.getClassId());
                                re.setCourseId(a.getCourseId());
                                re.setTime(a.getTime());
                                re.setInResult("4");//签到状态(1-正常 2-迟到4-缺勤 )
                                re.setOutResult("-1");// //签退状态(1-正常  3-早退)
                                re.setAttendResult("4"); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退
                                re.setTermCode(a.getTermCode());//设备号
                                re.setLg("0");//签到签退标识0-签到，1-签退  -1 缺勤
                                re.setUserId(a.getUserId());
                                re.setIsUpload(a.getIsUpload());
                                re.setTag(a.getTag());
                                re.setSatrtTime(a.getSatrtTime());
                                re.setEndTime(a.getEndTime());

                                mRecordDao.update(re);

                            } else if (a == null && b != null) {//2: 有签到 ，无签退记录， 更新签到的结果数据 更新   attendResult =4;   lg=0-签到
                                Log.d(TAG, "2: 有签退 ，无签到记录， 更新签到的结果数据 更新   attendResult =4;   lg= 1 签退");//更新签到记录
                                Record re = new Record();
                                re.setId(b.getId());
                                re.setWlkh(b.getWlkh());
                                re.setClassId(b.getClassId());
                                re.setCourseId(b.getCourseId());
                                re.setTime(b.getTime());
                                re.setInResult("4");//签到状态(1-正常 2-迟到4-缺勤 )
                                re.setOutResult("-1");// //签退状态(1-正常  3-早退)
                                re.setAttendResult("4"); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退
                                re.setTermCode(b.getTermCode());//设备号
                                re.setLg("1");//签到签退标识0-签到，1-签退  -1 缺勤
                                re.setUserId(b.getUserId());
                                re.setIsUpload(b.getIsUpload());
                                re.setTag(b.getTag());
                                re.setSatrtTime(b.getSatrtTime());
                                re.setEndTime(b.getEndTime());

                                mRecordDao.update(re);

                            } else if (a != null && b != null) {
                                Log.d(TAG, "1：有签到，签退 记录，   更新 签退  attendResult");
                                Record re = new Record();
                                re.setId(b.getId());
                                re.setWlkh(b.getWlkh());
                                re.setClassId(b.getClassId());
                                re.setCourseId(b.getCourseId());
                                re.setTime(b.getTime());

                                re.setInResult(a.getInResult());//签到状态(1-正常 2-迟到4-缺勤 )

                                re.setOutResult(b.getOutResult());// //签退状态(1-正常  3-早退)

                                String aR = a.getInResult();
                                String bR = b.getOutResult();
                                String strAttendResult = "";
                                if (aR.equals("1") && bR.equals("1")) {//1-正常
                                    strAttendResult = "1";
                                } else if (aR.equals("2") && bR.equals("1")) {//2-迟到
                                    strAttendResult = "2";
                                } else if (aR.equals("1") && bR.equals("3")) {//3-早退
                                    strAttendResult = "3";
                                } else if (aR.equals("4") && bR.equals("1")) {// 4-缺勤
                                    strAttendResult = "4";
                                } else if (aR.equals("2") && bR.equals("3")) {//5-迟到早退
                                    strAttendResult = "5";
                                }
                                re.setAttendResult(strAttendResult); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退

                                re.setTermCode(b.getTermCode());//设备号
                                re.setLg(b.getLg());//签到签退标识0-签到，1-签退  -1 缺勤
                                re.setUserId(b.getUserId());
                                re.setIsUpload(b.getIsUpload());
                                re.setTag(b.getTag());
                                re.setSatrtTime(b.getSatrtTime());
                                re.setEndTime(b.getEndTime());

                                mRecordDao.update(re);
                            }

                        }
                    }
                } else {//按节次
                    for (int i = 0; i < mlSize; i++) {
                        String fixId = mList.get(i).getFactoryfixId();
                        if (mList.get(i).getUseState() == 0) {//无效数据
                            Log.d(TAG, "无效数据 fixId=" + mList.get(i).getFactoryfixId());
                            continue;
                        }
                        //3：无签到，无签退，lg -1  attendResult 4  Time = null
                        Record a = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(strClassId), RecordDao.Properties.CourseId.eq(strCourseUuid), RecordDao.Properties.Wlkh.eq(fixId), RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.Tag.eq("in"), RecordDao.Properties.Time.isNotNull()).unique();
                        Record b = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(strClassId), RecordDao.Properties.CourseId.eq(strCourseUuid), RecordDao.Properties.Wlkh.eq(fixId), RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.Tag.eq("out"), RecordDao.Properties.Time.isNotNull()).unique();
                        if (a == null && b == null) {

                            Log.d(TAG, "3：无签到，无签退，lg -1  attendResult 4  Time = null"); //更新默认记录
                            Record mR = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(strClassId), RecordDao.Properties.CourseId.eq(strCourseUuid), RecordDao.Properties.Wlkh.eq(fixId), RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.Time.isNull()).unique();
                            if (null == mR) {
                                continue;
                            }
                            Record re = new Record();
                            re.setId(mR.getId());
                            re.setWlkh(mR.getWlkh());
                            re.setClassId(mR.getClassId());
                            re.setCourseId(mR.getCourseId());
                            re.setTime(null);
                            re.setInResult("4");//签到状态(1-正常 2-迟到4-缺勤 )
                            re.setOutResult("-1");// //签退状态(1-正常  3-早退)
                            re.setAttendResult("4"); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退
                            re.setTermCode(mR.getTermCode());//设备号
                            re.setLg("-1");//签到签退标识0-签到，1-签退  -1 缺勤
                            re.setUserId(mR.getUserId());
                            re.setIsUpload(mR.getIsUpload());
                            re.setTag(mR.getTag());
                            re.setSatrtTime(mR.getSatrtTime());
                            re.setEndTime(mR.getEndTime());

                            mRecordDao.update(re);

                        } else if (a != null && b == null) {//2: 有签到 ，无签退记录， 更新签到的结果数据 更新   attendResult =4;   lg=0-签到
                            Log.d(TAG, "2: 有签到 ，无签退记录， 更新签到的结果数据 更新   attendResult =4;   lg= 0 签到");//更新签到记录
                            Record re = new Record();
                            re.setId(a.getId());
                            re.setWlkh(a.getWlkh());
                            re.setClassId(a.getClassId());
                            re.setCourseId(a.getCourseId());
                            re.setTime(a.getTime());
                            re.setInResult("4");//签到状态(1-正常 2-迟到4-缺勤 )
                            re.setOutResult("-1");// //签退状态(1-正常  3-早退)
                            re.setAttendResult("4"); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退
                            re.setTermCode(a.getTermCode());//设备号
                            re.setLg("0");//签到签退标识0-签到，1-签退  -1 缺勤
                            re.setUserId(a.getUserId());
                            re.setIsUpload(a.getIsUpload());
                            re.setTag(a.getTag());
                            re.setSatrtTime(a.getSatrtTime());
                            re.setEndTime(a.getEndTime());

                            mRecordDao.update(re);

                        } else if (a == null && b != null) {//2: 有签到 ，无签退记录， 更新签到的结果数据 更新   attendResult =4;   lg=0-签到
                            Log.d(TAG, "2: 有签退 ，无签到记录， 更新签到的结果数据 更新   attendResult =4;  lg= 1 签退");//更新签到记录
                            Record re = new Record();
                            re.setId(b.getId());
                            re.setWlkh(b.getWlkh());
                            re.setClassId(b.getClassId());
                            re.setCourseId(b.getCourseId());
                            re.setTime(b.getTime());
                            re.setInResult("4");//签到状态(1-正常 2-迟到4-缺勤 )
                            re.setOutResult("-1");// //签退状态(1-正常  3-早退)
                            re.setAttendResult("4"); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退
                            re.setTermCode(b.getTermCode());//设备号
                            re.setLg("1");//签到签退标识0-签到，1-签退  -1 缺勤
                            re.setUserId(b.getUserId());
                            re.setIsUpload(b.getIsUpload());
                            re.setTag(b.getTag());
                            re.setSatrtTime(b.getSatrtTime());
                            re.setEndTime(b.getEndTime());

                            mRecordDao.update(re);

                        } else if (a != null && b != null) {
                            Log.d(TAG, "1：有签到，签退 记录，   更新 签退  attendResult");
                            Record re = new Record();
                            re.setId(b.getId());
                            re.setWlkh(b.getWlkh());
                            re.setClassId(b.getClassId());
                            re.setCourseId(b.getCourseId());
                            re.setTime(b.getTime());

                            re.setInResult(a.getInResult());//签到状态(1-正常 2-迟到4-缺勤 )

                            re.setOutResult(b.getOutResult());// //签退状态(1-正常  3-早退)

                            String aR = a.getInResult();
                            String bR = b.getOutResult();
                            String strAttendResult = "";
                            if (aR.equals("1") && bR.equals("1")) {//1-正常
                                strAttendResult = "1";
                            } else if (aR.equals("2") && bR.equals("1")) {//2-迟到
                                strAttendResult = "2";
                            } else if (aR.equals("1") && bR.equals("3")) {//3-早退
                                strAttendResult = "3";
                            } else if (aR.equals("4") && bR.equals("1")) {// 4-缺勤
                                strAttendResult = "4";
                            } else if (aR.equals("2") && bR.equals("3")) {//5-迟到早退
                                strAttendResult = "5";
                            }
                            re.setAttendResult(strAttendResult); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退

                            re.setTermCode(b.getTermCode());//设备号
                            re.setLg(b.getLg());//签到签退标识0-签到，1-签退  -1 缺勤
                            re.setUserId(b.getUserId());
                            re.setIsUpload(b.getIsUpload());
                            re.setTag(b.getTag());
                            re.setSatrtTime(b.getSatrtTime());
                            re.setEndTime(b.getEndTime());

                            mRecordDao.update(re);
                        }

                    }
                }
            List<Record> mListIn;
            if (me.getCheckMode() == 2) {
                Log.d(TAG, "有签退模式：同一班级，不同课程的，同步数据");
                mListIn = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(me.getClassId()),
                        RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.EndTime.eq(strEndTime)
                ).list();
            } else {
                mListIn = mRecordDao.queryBuilder().where(RecordDao.Properties.CourseId.eq(mCourseId), RecordDao.Properties.ClassId.eq(me.getClassId()),
                        RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.EndTime.eq(strEndTime)
                ).list();
            }
            if (mListIn != null && mListIn.size() > 0) {
                String json = JSON.toJSONString(mListIn);
                Log.d(TAG, "listIn:" + mListIn.size());
                Log.d(TAG, "jsonIn:" + json);
                for (int i = 0; i < mListIn.size(); i++) {
                    Log.d(TAG, "listIn:" + mListIn.get(i).toString());
                }
                UpLoadJSON(json, isAbUpload);
            }

        }


    }

    private void UpLoadJSON(final String json, final boolean isAbUpload) {

        Subscriber subscr = new AbsAPICallback<Resutl>(this) {
            @Override
            public void onCompleted() {
                Log.d(TAG, "onCompleted--");

            }


            @Override
            public void onNext(Resutl resul) {
                if (resul != null) {
                    Log.d(TAG, "Message" + resul.getMessage() + " Code:" + resul.isCode());
                    if (resul.isCode()) {
                        Log.d(TAG, "Message 批量更新 上传过的数据--");
                        final List<Record> mList = JsonListUtil.jsonToList(json, Record.class);
                        if (mList != null && mList.size() > 0) {
                            ThreadUtil.getInstance().submit(new Runnable() {
                                @Override
                                public void run() {
                                    for (int i = 0; i < mList.size(); i++) {
                                        if (!isAbUpload) {
                                            Record a = mRecordDao.queryBuilder().where(RecordDao.Properties.Id.eq(mList.get(i).getId())).unique();
                                            if (a != null) {
                                                mRecordDao.deleteByKey(a.getId());
                                                realmHelper.deleteDogAll(TempBean.class);
                                                //清除集合，更新listView
                                              /*  if(null!= mListBean){
                                                    mListBean.clear();
                                                    initAdapter();
                                                }*/
                                                MyFileUtils.deleteFile(MyFileUtils.mListBean);
                                                MyFileUtils.deleteFile(MyFileUtils.mListAttachUrl);
                                                List<MeetingResutl> mlist = new ArrayList<MeetingResutl>();
                                                if ((BigenCard.size() - 1) == indexBigen) {//上传后 最后 一次清空课程表信息
                                                    setupViews(R.layout.layout_depar, R.layout.layout_department, R.id.layout_more, R.id.tiee, mlist, 0);
                                                }

                                            }
                                        }
                                    }
                                }
                            });

                        }
                    }


                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                if (e != null) {
                    Log.i(TAG, "e：" + e.getMessage());
                    Log.d(TAG, "上传失败");
                }


            }
        };
        Api.getInstance().UploadCheck(subscr, json);
    }


    private String isOutTimeRuleFunc(String dateStr, int outBefore, int outLate, int leaveEarly, String flag) {
        String result = "";
        try {

            SimpleDateFormat simhm = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date targetDate1 = simhm.parse(dateStr);
            String dataStrhms = DateStrHMS(targetDate1);

            SimpleDateFormat sim = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date targetDate = sim.parse(dataStrhms);


            long targetTime = targetDate.getTime() / 1000 / 60;
            long before = targetTime - outBefore;
            long after = targetTime + outLate;//签退延迟分钟
            long early = targetTime - leaveEarly;//早退分钟

            String strCurrent = DatetimeUtil.getSysDate("yyyy-MM-dd HH:mm:ss");
            Date currentDate = sim.parse(strCurrent);
            long current = currentDate.getTime() / 1000 / 60;
            if (before <= current && current < early) {
                Log.d(TAG, "早退！！");
                result = flag + "late";

            } else if (early <= current && current < after) {
                Log.d(TAG, "签退正常！！");
                result = flag + "valid";
            } else {
                Log.d(TAG, "无效！！");
                result = flag + "invalid";
            }
         /*   if (before <= current && current <= after) {
                Log.d(TAG, "签退正常！！");
                result = flag + "valid";
            } else if (early <= current && current <= before) {
                Log.d(TAG, "早退！！");
                result = flag + "late";
            } else {
                Log.d(TAG, "无效！！");
                result = flag + "invalid";
            }*/
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, e.getMessage());
        }
        return result;
    }

    private String isInTimeRuleFunc(String dateStr, int inBefore, int beLate, int absenteeism, String flag) {
        String result = "";
        try {

            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date targetDate = sim.parse(dateStr);
            long targetTime = targetDate.getTime() / 1000 / 60;
            long before = targetTime - inBefore;
            long after = targetTime + beLate;//迟到时间
            long late = targetTime + absenteeism;//旷课时间

            String strCurrent = DatetimeUtil.getSysDate("yyyy-MM-dd HH:mm");
            Log.d(TAG, "strCurrent" + strCurrent);
            Date currentDate = sim.parse(strCurrent);
            long current = currentDate.getTime() / 1000 / 60;

            if (before <= current && current <= after) {
                Log.d(TAG, "签到正常！！");
                result = flag + "valid";
            } else if (after <= current && current <= late) {
                Log.d(TAG, "迟到！！");
                result = flag + "late";
            } else {
                Log.d(TAG, "无效！！");
                result = flag + "invalid";
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("HH", e.getMessage());
        }
        return result;
    }


      /*  for (int j = 0; j < CourseId.size(); j++) {
            List<PersonnelResutl> list = realmHelper.querPersonne(CourseId.get(j));

            for (int i = 0; i < list.size(); i++) {
                if (realmHelper.queryDogMeeting(list.get(i).getCourseId(), list.get(i).getUserId()).size() == 0) {
                    MeetingCheck meetingCheck = new MeetingCheck();
                    meetingCheck.setClassId(list.get(i).getClassId());

               *//*    String targetIn = isInTimeRuleFunc( BigenCard.get(indexBigen),me.getInBefore(),me.getBeLate(),me.getAbsenteeism(),"IN_");
                    switch (targetIn) {
                        case "IN_valid":

                            break;
                        case "IN_late":
                            break;
                        case "IN_invalid":
                            break;
                    }*//*
//                    meetingCheck.setInResult("4");
//                    meetingCheck.setCourseId(list.get(i).getCourseId());
//                    meetingCheck.setTermCode(mSharePreferenceUtil.getClassId());
//                    meetingCheck.setLg("-1");
//                    meetingCheck.setTime(null);
//                    meetingCheck.setWlkh(list.get(i).getWlkh());
//                    meetingCheck.setOutResult("0");
//                    meetingCheck.setAttendResult("4");
//                    meetingCheck.setUserId(list.get(i).getUserId());
//                    realmHelper.addDog(meetingCheck);
                }
            }
        }

*/

//    MeetingResutl meetingResutl;


    //如果有2条以上或者2条 而且开启签退 取第一条和最后一条，不然取第一条
//    private void UploadCheck() {
//        meetingResutl = (MeetingResutl) realmHelper.querMeetingResutll(CourseId.get(mSharePreferenceUtil.getIndexBigen()), class_attemdamce.get(mSharePreferenceUtil.getIndexBigen())).get(0);
//        BigenCard = MyApp.getsInstance().getBigenCard();
//        CourseId = MyApp.getsInstance().getCourseId();
//        if (list.size() != 0) {
//            list = realmHelper.queryDobByAge(CourseId.get(mSharePreferenceUtil.getIndexBigen()), class_attemdamce.get(mSharePreferenceUtil.getIndexBigen()));
//            if (meetingResutl.getCheckMode() == 1) {
//                for (int i = 0; i < list.size(); i++) {
//                    if (realmHelper.QueryTraineeId(list.get(i).getUserId(), list.get(i).getCourseId()).size() == 0) {
//                        MeetingCheck meetingCheck = new MeetingCheck();
//                        meetingCheck.setClassId(list.get(i).getClassId());
//                        meetingCheck.setInResult("4");
//                        meetingCheck.setCourseId(list.get(i).getCourseId());
//                        meetingCheck.setTermCode(mSharePreferenceUtil.getClassId());
//                        meetingCheck.setLg("-1");
//                        meetingCheck.setTime(null);
//                        meetingCheck.setWlkh(list.get(i).getWlkh());
//                        meetingCheck.setOutResult("0");
//                        meetingCheck.setAttendResult("4");
//                        meetingCheck.setUserId(list.get(i).getUserId());
//                        realmHelper.addDog(meetingCheck);
//                    }
//                    if (mSharePreferenceUtil.getNeedCheckout() == 1) {
//                        if (realmHelper.QueryTraineeId(list.get(i).getUserId(), list.get(i).getCourseId()).size() == 1) {
//                            if (DatetimeUtil.Getminutes(realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime(), BigenCard.get(indexBigen)) <= (meetingResutl.getOutBefore() + meetingResutl.getAbsenteeism())) {
//                                realmHelper.updateInResultOne(list.get(i).getWlkh(), "1");
//                            } else {
//                                realmHelper.updateInResultOne(list.get(i).getWlkh(), "2");
//
//                            }
//                            if (DatetimeUtil.Getminutes(realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getTime(), EndCard.get(indexEnd)) <= (meetingResutl.getOutBefore() + meetingResutl.getOutLate())) {
//                                realmHelper.updateOutResultOne(list.get(i).getWlkh(), "1");
//
//                            }
//
//                            if (DatetimeUtil.Getminutes(EndCard.get(indexEnd), realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getTime()) <= (meetingResutl.getOutBefore() + meetingResutl.getLeaveEarly())) {
//                                realmHelper.updateOutResultOne(list.get(i).getWlkh(), "1");
//
//                            } else {
//                                realmHelper.updateOutResult(list.get(i).getWlkh(), "3");
//
//                            }
//
//                            if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("1") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("1")) {
//                                realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "1");
//
//                            } else if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("2") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("1")) {
//                                realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "2");
//
//                            } else if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("1") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("3")) {
//                                realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "3");
//
//                            } else if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("2") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("3")) {
//                                realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "5");
//
//                            } else {
//                                realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult());
//                                realmHelper.updateAttendResult(list.get(i).getWlkh(), realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult());
//                            }
//                            realmHelper.UpdateLgOne(list.get(i).getWlkh(), "0");  //改状态
//                            if (DatetimeUtil.Getminutes(realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime(), BigenCard.get(indexBigen)) <= (meetingResutl.getBeLate() + meetingResutl.getAbsenteeism())) {
//                                realmHelper.updateInResultOne(list.get(i).getWlkh(), "1");
//
//                            } else {
//                                realmHelper.updateInResultOne(list.get(i).getWlkh(), "2");
//                            }
//                            if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime() == null) {
//                                realmHelper.UpdateLgOne(list.get(i).getWlkh(), "-1");
//                                realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "4");
//                            }
////
//
//                        } else if (realmHelper.QueryTraineeId(list.get(i).getUserId(), list.get(i).getCourseId()).size() >= 2) {
//                            Log.d("TAG", "2");
//                            realmHelper.UpdateLgLate(list.get(i).getWlkh());
//                            realmHelper.UpdateLgOne(list.get(i).getWlkh(), "0");
//                            if (DatetimeUtil.Getminutes(realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime(), BigenCard.get(indexBigen)) <= (meetingResutl.getBeLate() + meetingResutl.getAbsenteeism())) {
//                                realmHelper.updateInResultOne(list.get(i).getWlkh(), "1");
//                                realmHelper.updateInResult(list.get(i).getWlkh(), "1");
//                            } else {
//                                realmHelper.updateInResultOne(list.get(i).getWlkh(), "2");
//                                realmHelper.updateInResult(list.get(i).getWlkh(), "2");
//                            }
//                            if (DatetimeUtil.Getminutes(realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getTime(), EndCard.get(indexEnd)) <= (meetingResutl.getOutBefore() + meetingResutl.getOutLate())) {
//                                realmHelper.updateOutResultOne(list.get(i).getWlkh(), "1");
//                                realmHelper.updateOutResult(list.get(i).getWlkh(), "1");
//                            }
//                            if (DatetimeUtil.Getminutes(EndCard.get(indexEnd), realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getTime()) <= (meetingResutl.getOutBefore() + meetingResutl.getLeaveEarly())) {
//                                realmHelper.updateOutResultOne(list.get(i).getWlkh(), "1");
//                                realmHelper.updateOutResult(list.get(i).getWlkh(), "1");
//                            } else {
//                                realmHelper.updateOutResult(list.get(i).getWlkh(), "3");
//                                realmHelper.updateOutResultOne(list.get(i).getWlkh(), "3");
//                            }
//
//                            if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("1") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("1")) {
//                                realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "1");
//                                realmHelper.updateAttendResult(list.get(i).getWlkh(), "1");
//                            } else if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("2") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("1")) {
//                                realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "2");
//                                realmHelper.updateAttendResult(list.get(i).getWlkh(), "2");
//                            } else if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("1") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("3")) {
//                                realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "3");
//                                realmHelper.updateAttendResult(list.get(i).getWlkh(), "3");
//                            } else if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("2") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("3")) {
//                                realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "5");
//                                realmHelper.updateAttendResult(list.get(i).getWlkh(), "5");
//                            } else {
//                                realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult());
//                                realmHelper.updateAttendResult(list.get(i).getWlkh(), realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult());
//                            }
//
//                        }
//                        if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime() == null) {
//                            realmHelper.UpdateLgOne(list.get(i).getWlkh(), "-1");
//                            realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "4");
//                        }
//
//                        if (realmHelper.QueryTraineeId(list.get(i).getUserId(), list.get(i).getCourseId()).size() >= 2) {
//                            list1.add(realmHelper.QueryTraineeIdOne(list.get(i).getUserId(), list.get(i).getCourseId(), 1));
//                            list1.add(realmHelper.QueryTraineeIdOne(list.get(i).getUserId(), list.get(i).getCourseId(), 2));
//                        } else if (realmHelper.QueryTraineeId(list.get(i).getUserId(), list.get(i).getCourseId()).size() == 1 || realmHelper.QueryTraineeId(list.get(i).getUserId(), list.get(i).getCourseId()).size() == 0) {
//                            list1.add(realmHelper.QueryTraineeIdOne(list.get(i).getUserId(), list.get(i).getCourseId(), 1));
//                        }
//                        Log.d("TAG", "开启签退");
//                    } else {//没开启签退
//                        if (realmHelper.QueryTraineeId(list.get(i).getUserId(), list.get(i).getCourseId()).size() >= 1) {
//                            if (DatetimeUtil.Getminutes(realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime(), BigenCard.get(indexBigen)) <= (meetingResutl.getBeLate() + meetingResutl.getAbsenteeism())) {
//                                realmHelper.updateInResultOne(list.get(i).getWlkh(), "1");
//                                realmHelper.updateAttendResult(list.get(i).getWlkh(), "1");
//                            } else {
//                                realmHelper.updateInResultOne(list.get(i).getWlkh(), "2");
//                                realmHelper.updateAttendResult(list.get(i).getWlkh(), "2");
//
//                            }
//                        }
//                        realmHelper.updateOutResultOne(list.get(i).getWlkh(), "1");
//                        realmHelper.UpdateLgOne(list.get(i).getWlkh(), "0");  //改状态
//                        if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime() == null) {
//                            realmHelper.UpdateLgOne(list.get(i).getWlkh(), "-1");
//                            realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "4");
//                        }
//
//
//                        list1.add(realmHelper.QueryTraineeIdOne(list.get(i).getUserId(), list.get(i).getCourseId(), 1));
//                        Log.d("TAG", "没开启签退");
//
//                    }
//
//                }
//            } else {
//                    for (int i = 0; i < list.size(); i++) {
//                        if (realmHelper.queryDogList(list.get(i).getWlkh(), list.get(i).getUserId()).size() == 0) {
//                            MeetingCheck meetingCheck = new MeetingCheck();
//                            meetingCheck.setClassId(list.get(i).getClassId());
//                            meetingCheck.setInResult("4");
//                            meetingCheck.setCourseId(list.get(i).getCourseId());
//                            meetingCheck.setTermCode(mSharePreferenceUtil.getClassId());
//                            meetingCheck.setLg("-1");
//                            meetingCheck.setTime(null);
//                            meetingCheck.setWlkh(list.get(i).getWlkh());
//                            meetingCheck.setOutResult("0");
//                            meetingCheck.setAttendResult("4");
//                            meetingCheck.setUserId(list.get(i).getUserId());
//                            realmHelper.addDog(meetingCheck);
//
//                        }
//                        if (meetingResutl.getNeedCheckout() == 1) {
//                            if (realmHelper.queryDogList(list.get(i).getWlkh(), list.get(i).getUserId()).size() == 1) {
//
//                                if (DatetimeUtil.Getminutes(realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime(), BigenCard.get(indexBigen)) <= (meetingResutl.getBeLate() + meetingResutl.getAbsenteeism())) {
//                                    realmHelper.updateInResultOne(list.get(i).getWlkh(), "1");
//                                } else {
//                                    realmHelper.updateInResultOne(list.get(i).getWlkh(), "2");
//
//                                }
//                                if (DatetimeUtil.Getminutes(realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getTime(), EndCard.get(indexEnd)) <= (meetingResutl.getOutBefore() + meetingResutl.getOutLate())) {
//                                    realmHelper.updateOutResultOne(list.get(i).getWlkh(), "1");
//
//                                }
//                                if (DatetimeUtil.Getminutes(EndCard.get(indexEnd), realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getTime()) <= (meetingResutl.getOutBefore() + meetingResutl.getLeaveEarly())) {
//                                    realmHelper.updateOutResultOne(list.get(i).getWlkh(), "1");
//
//                                } else {
//                                    realmHelper.updateOutResult(list.get(i).getWlkh(), "3");
//
//                                }
//
//                                if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("1") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("1")) {
//                                    realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "1");
//
//                                } else if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("2") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("1")) {
//                                    realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "2");
//
//                                } else if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("1") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("3")) {
//                                    realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "3");
//
//                                } else if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("2") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("3")) {
//                                    realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "5");
//
//                                } else {
//                                    realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult());
//                                    realmHelper.updateAttendResult(list.get(i).getWlkh(), realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult());
//                                }
//                                realmHelper.UpdateLgOne(list.get(i).getWlkh(), "0");  //改状态
//                                if (DatetimeUtil.Getminutes(realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime(), BigenCard.get(indexBigen)) <= (meetingResutl.getBeLate() + meetingResutl.getAbsenteeism())) {
//                                    realmHelper.updateInResultOne(list.get(i).getWlkh(), "1");
//
//                                } else {
//                                    realmHelper.updateInResultOne(list.get(i).getWlkh(), "2");
//                                }
//                                if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime() == null) {
//                                    realmHelper.UpdateLgOne(list.get(i).getWlkh(), "-1");
//                                    realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "4");
//                                }
////
//
//
//                            } else if (realmHelper.queryDogList(list.get(i).getWlkh(), list.get(i).getUserId()).size() >= 2) {
//
//
//                                realmHelper.UpdateLgLate(list.get(i).getWlkh());
//                                realmHelper.UpdateLgOne(list.get(i).getWlkh(), "0");
//                                if (DatetimeUtil.Getminutes(realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime(), BigenCard.get(indexBigen)) <= (meetingResutl.getBeLate() + meetingResutl.getAbsenteeism())) {
//                                    realmHelper.updateInResultOne(list.get(i).getWlkh(), "1");
//                                    realmHelper.updateInResult(list.get(i).getWlkh(), "1");
//                                } else {
//                                    realmHelper.updateInResultOne(list.get(i).getWlkh(), "2");
//                                    realmHelper.updateInResult(list.get(i).getWlkh(), "2");
//                                }
//                                if (DatetimeUtil.Getminutes(realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getTime(), EndCard.get(indexEnd)) <= (meetingResutl.getOutBefore() + meetingResutl.getOutLate())) {
//                                    realmHelper.updateOutResultOne(list.get(i).getWlkh(), "1");
//                                    realmHelper.updateOutResult(list.get(i).getWlkh(), "1");
//                                }
//                                if (DatetimeUtil.Getminutes(EndCard.get(indexEnd), realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getTime()) <= (meetingResutl.getOutBefore() + meetingResutl.getLeaveEarly())) {
//                                    realmHelper.updateOutResultOne(list.get(i).getWlkh(), "1");
//                                    realmHelper.updateOutResult(list.get(i).getWlkh(), "1");
//                                } else {
//                                    realmHelper.updateOutResult(list.get(i).getWlkh(), "3");
//                                    realmHelper.updateOutResultOne(list.get(i).getWlkh(), "3");
//                                }
//
//
//                                if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("1") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("1")) {
//                                    realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "1");
//                                    realmHelper.updateAttendResult(list.get(i).getWlkh(), "1");
//                                } else if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("2") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("1")) {
//                                    realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "2");
//                                    realmHelper.updateAttendResult(list.get(i).getWlkh(), "2");
//                                } else if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("1") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("3")) {
//                                    realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "3");
//                                    realmHelper.updateAttendResult(list.get(i).getWlkh(), "3");
//                                } else if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult().equals("2") && realmHelper.queryDogByIdLast(list.get(i).getWlkh()).getOutResult().equals("3")) {
//                                    realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "5");
//                                    realmHelper.updateAttendResult(list.get(i).getWlkh(), "5");
//                                } else {
//                                    realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult());
//                                    realmHelper.updateAttendResult(list.get(i).getWlkh(), realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getInResult());
//                                }
//
//
//                            }
//
//                            if (CourseId.size() == 2) {
//                                realmHelper.updateAttendcourseId(list.get(i).getWlkh(), CourseId.get(0) + "," + CourseId.get(1));
//                            } else if (CourseId.size() == 3) {
//                                realmHelper.updateAttendcourseId(list.get(i).getWlkh(), CourseId.get(0) + "," + CourseId.get(1) + "," + CourseId.get(2));
//
//                            }
//                            if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime() == null) {
//                                realmHelper.UpdateLgOne(list.get(i).getWlkh(), "-1");
//                                realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "4");
//                            }
//
//                            if (realmHelper.queryDogList(list.get(i).getWlkh(), list.get(i).getUserId()).size() >= 2) {
//                                list1.add(realmHelper.QueryTraineeId(list.get(i).getUserId(), list.get(i).getClassId(), 1));
//                                list1.add(realmHelper.QueryTraineeId(list.get(i).getUserId(), list.get(i).getClassId(), 2));
//                            } else if (realmHelper.queryDogList(list.get(i).getWlkh(), list.get(i).getUserId()).size() == 1 || realmHelper.queryDogList(list.get(i).getWlkh(), list.get(i).getUserId()).size() == 0) {
//                                list1.add(realmHelper.QueryTraineeId(list.get(i).getUserId(), list.get(i).getClassId(), 1));
//                            }
//
//                        } else {
//                            if (realmHelper.queryDogList(list.get(i).getWlkh(), list.get(i).getUserId()).size() >= 1) {     //    迟到分钟加缺勤分钟
//                                if (DatetimeUtil.Getminutes(realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime(), BigenCard.get(indexBigen)) <= (meetingResutl.getBeLate() + meetingResutl.getAbsenteeism())) {
//                                    realmHelper.updateInResultOne(list.get(i).getWlkh(), "1");
//                                    realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "1");
//                                } else {
//                                    realmHelper.updateInResultOne(list.get(i).getWlkh(), "2");
//                                    realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "2");
//
//                                }
//
//                                realmHelper.UpdateLgOne(list.get(i).getWlkh(), "0");  //改状态
//                                realmHelper.updateOutResultOne(list.get(i).getWlkh(), "1");
//
//                                if (CourseId.size() == 2) {
////                                    meetingCheck.setCourseId(CourseId.get(0)+","+CourseId.get(1));
//                                    realmHelper.updateAttendcourseId(list.get(i).getWlkh(), CourseId.get(0) + "," + CourseId.get(1));
//                                } else if (CourseId.size() == 3) {
//                                    realmHelper.updateAttendcourseId(list.get(i).getWlkh(), CourseId.get(0) + "," + CourseId.get(1) + "," + CourseId.get(2));
//                                }
//                                if (realmHelper.queryDogByIdOne(list.get(i).getWlkh()).getTime() == null) {
//                                    realmHelper.UpdateLgOne(list.get(i).getWlkh(), "-1");
//                                    realmHelper.updateAttendResultOne(list.get(i).getWlkh(), list.get(i).getUserId(), "4");
//                                }
//
//                                list1.add(realmHelper.QueryTraineeId(list.get(i).getUserId(), list.get(i).getClassId(), 1));
//
//                            }
//
//
//                        }
//                    }
//                    class_attemdamce = MyApp.getsInstance().getClass_attemdamce();
//                }
//            }
//
//
//        }
//
//
//        mSharePreferenceUtil.setDataFig(true);
//        String json = JSON.toJSONString(list1);
//        Log.d("TAG", "json:" + json);
//        Log.d("TAG", "list1:" + list1.size());
//        Subscriber subscr = new AbsAPICallback<Resutl>(this) {
//            @Override
//            public void onCompleted() {
//                Log.d(TAG, "上传失败");
//            }
//
//
//            @Override
//            public void onNext(Resutl resul) {
//                Log.d(TAG, "上传成功");
//                Log.d(TAG, "上resul:" + resul);
//                if (resul.isCode()) {
////                    if (getSysDate("yyyy-MM-dd HH:mm:ss").equals(DatetimeUtil.getDateTimeFromMillisecond(
////                            DatetimeUtil.TimeStrToSecond(EndCard.get(EndCard.size() - 1)) + 1000 * 60 * meetingResutl.getLeaveEarly()))) {
////                        realmHelper.deleteDogAll(MeetingCheck.class);
////                    }
////                    realmHelper.deleteDogMeeting(CourseId.get(indexBigen - 1), class_attemdamce.get(indexBigen - 1));
//
//                    list1.clear();
//                    mSharePreferenceUtil.setRealized(0);
//                    mSharePreferenceUtil.setFig(false);
//                    mSharePreferenceUtil.setDataFig(false);
//
//                }
//
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                super.onError(e);
//                Log.i("TAG", "e：" + e.getMessage());
//                Log.d("TAG", "上传失败");
//            }
//        };
//        //   Api.getInstance().UploadCheck(subscr, json);
//
//
//    }


    private class SufaceListener implements SurfaceHolder.Callback {
        private boolean isPreview;

        @Override
        public void surfaceCreated(SurfaceHolder surfaceHolder) {
            try {
                WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
                Display display = wm.getDefaultDisplay();
                //int num = mCamera.getNumberOfCameras();
                mCamera = Camera.open(0);
                Camera.Parameters parameters = mCamera.getParameters();
                List<Camera.Size> vSizeList = parameters.getSupportedPictureSizes();

                for (int num = 0; num < vSizeList.size(); num++) {
                    Camera.Size vSize = vSizeList.get(num);
                }

                if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
                    //如果是竖屏
                    mCamera.setDisplayOrientation(90);
                } else {
                    mCamera.setDisplayOrientation(180);
                }
                parameters.setPictureFormat(PixelFormat.JPEG);
                mCamera.setParameters(parameters);
                mCamera.setPreviewDisplay(mSurfaceHolder);
                mCamera.startPreview();
                isPreview = true;

            } catch (Exception e) {
                Toast.makeText(ReMainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                Log.d("TAG", "e:" + e.getMessage());
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
            if (mSurfaceHolder == null) {
                // preview surface does not exist
                return;
            }

            // stop preview before making changes
            try {
                if (mCamera != null) {
                    mCamera.stopPreview();

                }

            } catch (Exception e) {
                // ignore: tried to stop a non-existent preview
            }

            try {
                mCamera.setPreviewDisplay(mSurfaceHolder);
                mCamera.startPreview();

            } catch (Exception e) {

            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
            if (mCamera != null) {
                if (isPreview) mCamera.stopPreview();
                mCamera.release();
                mCamera = null;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy-----");
        //销毁activity之前先关闭定时器
        if (handler != null) {
            if (timeadv != null) {
                handler.removeCallbacks(timeadv);
            }
        }
        if (MyDialog != null) {
            MyDialog.dismiss();
            MyDialog = null;
        }
        mSharePreferenceUtil.setSubscript(false);
        RxBus.get().unregister(this);


    }

    private void loadMusic() {
        soundPool1 = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);

        q_dao_late = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        q_dao_s = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        q_ni_Already_dao = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        q_ni_Already_tui = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        q_ni_buzaibenban_q = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        q_tui_late = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        q_tui_s = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        q_wu_ni_ke = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        q_wukecheng = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);

        sourceid = soundPool1.load(this, R.raw.failure, 0);


        sourceid = q_dao_late.load(this, R.raw.q_dao_late, 0);
        sourceid = q_dao_s.load(this, R.raw.q_dao_s, 0);
        sourceid = q_ni_Already_dao.load(this, R.raw.q_ni_already_dao, 0);
        sourceid = q_ni_Already_tui.load(this, R.raw.q_ni_already_tui, 0);
        sourceid = q_ni_buzaibenban_q.load(this, R.raw.q_ni_buzaibenban_q, 0);
        sourceid = q_tui_late.load(this, R.raw.q_tui_late, 0);
        sourceid = q_tui_s.load(this, R.raw.q_tui_s, 0);
        sourceid = q_wu_ni_ke.load(this, R.raw.q_wu_ni_ke, 0);
        sourceid = q_wukecheng.load(this, R.raw.q_wukecheng, 0);

        soundPool1
                .setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

                    public void onLoadComplete(SoundPool soundPool,
                                               int sampleId, int status) {
                        isSoundReady = true;

                    }
                });

        q_dao_late
                .setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

                    public void onLoadComplete(SoundPool soundPool,
                                               int sampleId, int status) {
                        isSoundReady = true;

                    }
                });
        q_dao_s
                .setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

                    public void onLoadComplete(SoundPool soundPool,
                                               int sampleId, int status) {
                        isSoundReady = true;

                    }
                });
        q_ni_Already_dao
                .setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

                    public void onLoadComplete(SoundPool soundPool,
                                               int sampleId, int status) {
                        isSoundReady = true;

                    }
                });

        q_ni_Already_tui
                .setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

                    public void onLoadComplete(SoundPool soundPool,
                                               int sampleId, int status) {
                        isSoundReady = true;

                    }
                });
        q_ni_buzaibenban_q
                .setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

                    public void onLoadComplete(SoundPool soundPool,
                                               int sampleId, int status) {
                        isSoundReady = true;

                    }
                });
        q_tui_late
                .setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

                    public void onLoadComplete(SoundPool soundPool,
                                               int sampleId, int status) {
                        isSoundReady = true;

                    }
                });


        q_tui_s
                .setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

                    public void onLoadComplete(SoundPool soundPool,
                                               int sampleId, int status) {
                        isSoundReady = true;

                    }
                });
        q_wu_ni_ke
                .setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

                    public void onLoadComplete(SoundPool soundPool,
                                               int sampleId, int status) {
                        isSoundReady = true;

                    }
                });
        q_wukecheng
                .setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

                    public void onLoadComplete(SoundPool soundPool,
                                               int sampleId, int status) {
                        isSoundReady = true;

                    }
                });


    }


    private void SetData(TextView tiem) {
        date.setText(getSysDate("yyyy年MM月dd日"));
        week.setText("星期" + DatetimeUtil.getWhere());
        tiem.setText(getSysDate("HH:mm:ss"));
    }

    public class MyThread implements Runnable {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                try {
                    Thread.sleep(1000);//线程暂停1秒，单位毫秒
                    Message message = new Message();
                    message.what = 3;
                    handler.sendMessage(message);//发送消息
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }


    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.set:
                SetDiagFragment setDiagFragment = new SetDiagFragment();
                setDiagFragment.show(getFragmentManager(), SetDiagFragment.class.getName());

                break;
        }
    }


    private <VT extends View> VT getView(@IdRes int id) {
        return (VT) findViewById(id);
    }

    private void initAdapter() {
        if (mAdapter == null) {
            mAdapter = new RecordAdapter(this, mListBean);
            listView.setAdapter(mAdapter);
        }
        mAdapter.notifyDataSetChanged();

    }

    private void setAdapterUI(String fixId, boolean isTui) {
        realized = mSharePreferenceUtil.getRealized();
        String mCurrentTimeHMS = DatetimeUtil.getSysDate("HH:mm:ss");
        if (mListBean != null && mListBean.size() > 0) {
            //mListBean.get(0).setmCurrenTime(DatetimeUtil.getSysDate("yyyy-MM-dd HH:mm:ss"));
            int size = mListBean.size();
            //默认时间
          /*  for (int i = 0; i < size; i++) {
                mListBean.get(i).setmCurrenTime("0");//DatetimeUtil.getSysDate("yyyy-MM-dd HH:mm:ss")
            }*/
            //
            for (int i = 0; i < size; i++) {
                if (mListBean.get(i).getFactoryfixId().equals(fixId)) {
                    if (mListBean.get(i).getType() == 0 && !isTui) {
                        realized++;
                        mSharePreferenceUtil.setRealized(realized);
                        mListBean.get(i).setType(1);
                        mListBean.get(i).setmCurrenTime(DatetimeUtil.getSysDate("yyyy-MM-dd HH:mm:ss"));
                        mListBean.get(i).setTime(mCurrentTimeHMS);
                        Log.d("TTTT1", mListBean.get(i).getmCurrenTime());

                    } else if (isTui) {//签退
                        realized++;
                        mSharePreferenceUtil.setRealized(realized);
                        mListBean.get(i).setType(2);
                        mListBean.get(i).setmCurrenTime(DatetimeUtil.getSysDate("yyyy-MM-dd HH:mm:ss"));
                        mListBean.get(i).setTime(mCurrentTimeHMS);
                        Log.d("TTTT2", mListBean.get(i).getmCurrenTime());
                    }

                    //
                    AttendanceResutl.CourseBean.ListBean bean = mListBean.get(i);
                    doSaveTempBean(bean);
                    //
                    break;
                }

            }
            Log.d("Www", "ss " + mSharePreferenceUtil.getRealized() + " realized" + realized);
            practical.setText(mSharePreferenceUtil.getRealized() + "/" + me.getExtField05() + "/" + mListBean.size() + "");

         /*   ThreadUtil.getInstance().submit(new Runnable() {
                @Override
                public void run() {
                    MyFileUtils.deleteFile(MyFileUtils.mListBean);
                    mListBean.get(0).setmCurrenTime(Bigen);
                    boolean isSave = MyFileUtils.saveObject2File(mListBean, MyFileUtils.mListBean);
                    Log.d(TAG, "刷卡保存--" + isSave);
                }
            });*/

            sortClass sort = new sortClass();
            Collections.sort(mListBean, sort);
            mAdapter.notifyDataSetChanged();

        }


    }

    private void doSaveTempBean(AttendanceResutl.CourseBean.ListBean b) {
        TempBean m = new TempBean();
        m.setFactoryfixId(b.getFactoryfixId());
        m.setmCurrenTime(b.getmCurrenTime());
        m.setCardNo(b.getCardNo());
        m.setUseState(b.getUseState());
        m.setClassId(b.getClassId());
        m.setType(b.getType());
        m.setTime(b.getTime());
        m.setXm(b.getXm());
        m.setTraineeId(b.getTraineeId());
        m.setIsLeave(b.getIsLeave());
        realmHelper.addTempBean(m);
        Log.d("TTTT2", "保存成功！！");


    }

    private class DispQueueThread extends Thread {
        private Queue<ComBean> QueueList = new LinkedList<ComBean>();

        @Override
        public void run() {
            super.run();
            while (!isInterrupted()) {
                final ComBean ComData;
                while ((ComData = QueueList.poll()) != null) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            DispRecData(ComData);
                        }
                    });
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }

        public synchronized void AddQueue(ComBean ComData) {
            QueueList.add(ComData);
        }
    }

    String cardId = "";// 当前 刷卡卡号临时变量
    private CountDownTimer mDownTimer;

    private void startDowntime() {
        if (null == mDownTimer) {
            initDownTime();
        } else {
            mDownTimer.start();
        }
    }

    private final int TIME = 1000 * 1;//每1秒更新界面 年月日 时分秒

    private void initDownTime() {
        mDownTimer = new CountDownTimer(TIME, 2500) {
            @Override
            public void onTick(long l) {

                Log.d("dowm==", "onTick--");
            }

            @Override
            public void onFinish() {
                Log.d("dowm==", "onFinish");
                if (null != myActivity) {
                    cardId = "";
                    Log.d("dowm==", "onFinish 1秒后 TIME isOne--cardId = 空");
                    mDownTimer.cancel();
                }

            }


        };
        mDownTimer.start();
    }

    private void DispRecData(ComBean ComRecData) {

        Log.d("res", MyFunc.ByteArrToHex(ComRecData.bRec));
        // 10/17直接获取ID
        String resData = MyFunc.ByteArrToHex(ComRecData.bRec).trim();
        Log.d("res", "resData.length=" + resData.length());
        if (resData.endsWith("6B BB") && resData.length() >= 38) {
            Log.d("res", "10/17直接获取ID");
            String re = resData.substring(resData.length() - 20, resData.length() - 9);
            System.out.println(re);
            String[] rr = re.split(" ");
            String[] dd = new String[4];
            StringBuilder sb = new StringBuilder();
            dd[0] = rr[3];
            dd[1] = rr[2];
            dd[2] = rr[1];
            dd[3] = rr[0];
            for (int i = 0; i < dd.length; i++) {
                System.out.println(dd[i]);
                sb.append(dd[i]);
            }
            String factoryFixID = sb.toString();


            Log.d("res", "物理卡号：factoryFixID=" + factoryFixID + "cardId=" + cardId);
            if (!TextUtils.isEmpty(factoryFixID)) {
                Log.d("res", "刷卡成功");
                Long strl = Long.parseLong(factoryFixID, 16);//parseUnsignedLong("AF58EDF7", 16);
                String fixId = strl.toString();
                Log.d("res", "cardInfo:fixId" + fixId);
                if (cardId.equals(factoryFixID)) {
                    Log.d("res", "连刷----");
                    startDowntime();
                    return;
                } else {
                    cardId = factoryFixID;
                    Log.d("res", "第一次刷----cardId -16=" + cardId + "cardId-10=");
                    Toast.makeText(myActivity,"["+resData+"]"+"长度："+resData.length()+" factoryFixID："+factoryFixID+" fixId:"+fixId+"fixId长度："+fixId.length(),Toast.LENGTH_LONG).show();


                    if (!isLoading) {
                        doExecCard(cardId);
                    } else {
                        Log.d("res", "正在上传中----");
                    }
                }
            }

         /*   String strFix="2941840887";

            if(!TextUtils.isEmpty(strFix)){
                strFix=Long.toHexString(Long.valueOf(strFix));
            }
            if(strFix.equalsIgnoreCase(sb.toString())){
                Log.d("res","刷卡成功");
            }else{
                Log.d("res","刷卡失败");
            }*/


        } else {
            Log.d("res", "获取数据异常--");
        }


    }


    void setRecvData(byte[] recv) {
        for (int i = 0; i < recv.length; i++) {
            RecvData[i] = recv[i];
        }
    }

    private void setValidDataFlag(boolean b) {
        // TODO Auto-generated method stub
        validDataFlag = b;
    }

    private boolean isValid() {
        // TODO Auto-generated method stub
        return validDataFlag;
    }

    Date startDate = null;
    long startTime = 0;

    private void doExecCard(String mFixId) {


        Log.d(TAG, "cardInfo:" + mFixId);
        Long strl = Long.parseLong(mFixId, 16);//parseUnsignedLong("AF58EDF7", 16);
        String fixId = strl.toString();
        Log.d(TAG, "cardInfo:fixId" + fixId);
        //测试
//        if (true) {
//            takePicture(fixId, "1001");
//            return;
//        }

        EndCard = MyApp.getsInstance().getEndCard();
        BigenCard = MyApp.getsInstance().getBigenCard();
        CourseId = MyApp.getsInstance().getCourseId();
        String mCurrentTime = DatetimeUtil.getSysDate("yyyy-MM-dd HH:mm:ss");//getSysDate(mTimeFormat);

        Log.d(TAG, "mCurrentTime=" + mCurrentTime);
        //物理卡号是否存在
        PersonnelResutl pe = null;
        MeetingResutl me = null;
        if ((ps != null && ps.size() > 0) && (mets != null && mets.size() > 0) && (CourseId != null && CourseId.size() > 0) && mets.size() > indexBigen) {
            me = mets.get(indexBigen);
            int psSize = ps.size();
            boolean isExit = false;
            for (int i = 0; i < psSize; i++) {
                String wlkh = ps.get(i).getWlkh();
                Log.d(TAG, "wlkh" + wlkh);
                String strFix = Long.toHexString(Long.valueOf(wlkh));
                Log.d(TAG, "strFix" + strFix);
                if (wlkh.equals(fixId) && ps.get(i).getUseState() != null && ps.get(i).getUseState() == 1) {
                    pe = ps.get(i);
                    isExit = true;
                    Log.d(TAG, "物理卡号存在！！");
                    break;
                }
            }

            if (!isExit) {
                q_ni_buzaibenban_q.play(1, 1, 1, 0, 0, 1);
                Toast.makeText(ReMainActivity.this, "您不在本班上课！", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "物理卡号不存在 或 此卡无效_你不在本班上课！！");
                return;
            }

        } else {
            Log.d(TAG, "没有课程信息！！本课程暂无课程");
            q_wukecheng.play(1, 1, 1, 0, 0, 1);
            return;
        }
        //是否在有效时区内
        if (BigenCard.size() != 0 && indexBigen < BigenCard.size() && indexEnd < EndCard.size()) {
            String strCourseUuid = me.getCourseId();
            String strClassId = me.getClassId();
            String strBigenTime = BigenCard.get(indexBigen);
            String strEndTime = EndCard.get(indexEnd);
            for (int i = 0; i < BigenCard.size(); i++) {
                Log.d(TAG, BigenCard.get(i).toString());
            }
            Log.d(TAG, "indexBigen=" + strBigenTime + "strEndTime=" + strEndTime + "strCourseUuid " + strCourseUuid + "indexEnd " + indexEnd);
            if (TextUtils.isEmpty(strBigenTime) || TextUtils.isEmpty(strEndTime)) {
                q_ni_buzaibenban_q.play(1, 1, 1, 0, 0, 1);
                Toast.makeText(ReMainActivity.this, "您不在本班上课！", Toast.LENGTH_SHORT).show();
                return;
            }

            //

            //

          /*  me.setInBefore(1);//提前分钟
            me.setBeLate(1);//迟到分钟
            me.setAbsenteeism(0);//缺勤 旷课分钟
            // 8：00分钟 7：50-8：02 正常，
            //8:02 - 8:03 迟到 默认缺勤

            me.setLeaveEarly(0);// 早退分钟
            me.setOutBefore(1);// 早退提前分钟
            me.setOutLate(1);// 签退延迟分钟*/
            //区域 8：26 - 8：02
            // 8：30分钟 8：24-8：28 早退，
            // 8：28-8：32 正常，
            //签到时区
            String Bigen = DatetimeUtil.getDateTimeFromMillisecond(DatetimeUtil.TimeStrToSecond(BigenCard.get(indexBigen)) - 1000 * 60 * me.getInBefore());// me.getInBefore() 提前分钟
            String End = DatetimeUtil.getDateTimeFromMillisecond(
                    DatetimeUtil.TimeStrToSecond(BigenCard.get(indexEnd)) + 1000 * 60 * me.getAbsenteeism());//迟到分钟
            boolean isArarTimeIn = DatetimeUtil.TimeCompare(DatetimeUtil.getSysDate("HH:mm"), DatetimeUtil.gethour(Bigen), DatetimeUtil.gethour(End));
            //签退时区
            String BigenOut = DatetimeUtil.getDateTimeFromMillisecond(DatetimeUtil.TimeStrToSecond(EndCard.get(indexBigen)) - 1000 * 60 * me.getLeaveEarly());// 早退分钟
            String EndOut = DatetimeUtil.getDateTimeFromMillisecond(
                    DatetimeUtil.TimeStrToSecond(EndCard.get(indexEnd)) + 1000 * 60 * me.getOutLate());// me.getOutLate()签退延迟分钟
            boolean isArarTimeOut = DatetimeUtil.TimeCompare(DatetimeUtil.getSysDate("HH:mm"), DatetimeUtil.gethour(BigenOut), DatetimeUtil.gethour(EndOut));


            Log.d("sss", "sys1" + DatetimeUtil.getSysDate("HH:mm"));
            Log.d("sss", "sys2" + DatetimeUtil.gethour(End));
            Log.d("sss", "sys3" + DatetimeUtil.gethour(BigenOut));
            Log.d("sss", "sys4" + DatetimeUtil.TimeCompare(DatetimeUtil.getSysDate("HH:mm"), DatetimeUtil.gethour(End), DatetimeUtil.gethour(BigenOut)));
            //签到时段//doTimeSlotIn(strBigenTime, mCurrentTime, me.getInBefore(),me.getAbsenteeism() )
            if (isArarTimeIn && !isFlagTui) {
                Log.d(TAG, "在签到时段--doTimeSlotIn");
                Log.d(TAG, "InBefore()=" + me.getInBefore() + "Absenteeism=" + me.getAbsenteeism() + "BeLate=" + me.getBeLate());
                Log.d(TAG, "fixId" + fixId + "strBigenTime" + strBigenTime);
                Record red = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(strClassId), RecordDao.Properties.CourseId.eq(strCourseUuid), RecordDao.Properties.Wlkh.eq(fixId), RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.Tag.eq("in")).unique();
                if (red != null) {
//                    soundPool_q_dao_f.play(1, 1, 1, 0, 0, 1);
                    q_ni_Already_dao.play(1, 1, 1, 0, 0, 1);
                    Toast.makeText(ReMainActivity.this, "您已签到！", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "已签到过了---");
                    Log.d(TAG, "在签到时段--doTimeSlotIn vreListE" + red.toString());
                    return;
                } else {
                    Log.d(TAG, "没有签到过---");

                }

                String targetIn = isInTimeRuleFunc(strBigenTime, me.getInBefore(), me.getBeLate(), me.getAbsenteeism(), "IN_");//

                Log.d(TAG, "没有签到过---targetIn" + targetIn);
                Log.d(TAG, "strClassId " + strClassId + "strCourseUuid " + strCourseUuid + "fixId " + fixId + "strBigenTime " + strBigenTime);
                Record a = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(strClassId), RecordDao.Properties.CourseId.eq(strCourseUuid), RecordDao.Properties.Wlkh.eq(fixId), RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.Tag.eq("")).unique();
                if (a != null) {
                    Log.d(TAG, "卡存在oooo");
                } else {
                    q_ni_buzaibenban_q.play(1, 1, 1, 0, 0, 1);
                    Toast.makeText(ReMainActivity.this, "您不在本班上课！", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "卡不存在！！");
                    return;
                }
                switch (targetIn) {
                    case "IN_valid":


                        if (a != null) {

                            Log.d(TAG, "reList re" + a.toString());
                            Record re = new Record();
                            re.setId(a.getId());
                            re.setWlkh(a.getWlkh());
                            re.setClassId(a.getClassId());
                            re.setCourseId(a.getCourseId());
                            re.setTime(mCurrentTime);
                            re.setInResult("1");//签到状态(1-正常 2-迟到4-缺勤 )
                            re.setOutResult("-1");// //签退状态(1-正常  3-早退)
                            re.setAttendResult("1"); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退
                            re.setTermCode(pe.getTermCode());//设备号
                            re.setLg("0");//签到签退标识0-签到，1-签退  -1 缺勤
                            re.setUserId(pe.getUserId());
                            re.setIsUpload(a.getIsUpload());
                            re.setTag("in");
                            re.setSatrtTime(a.getSatrtTime());
                            re.setEndTime(a.getEndTime());

                            mRecordDao.update(re);
                            Log.d(TAG, a.toString());
                            setAdapterUI(fixId, false);
                            Handler sHandler = new Handler();
                            sHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    q_dao_s.play(1, 1, 1, 0, 0, 1);
                                    Toast.makeText(ReMainActivity.this, "签到成功！", Toast.LENGTH_SHORT).show();
                                }
                            }, 500);
                            takePicture(fixId, a.getUserId());

                            //特殊情况 同班级 且 半天考勤  //1:有可能2门 班级 一样 做同步处理
                            if (mSharePreferenceUtil.getIsSameClass() == 0 && me.getCheckMode() == 2) {// IsSameClass =0同班级 && CheckMode2 半天
                                Log.d(TAG, "IsSameClass =0同班级");
                                if (mets.size() == 3 && BigenCard.size() == 3) {//先判断课程 最多3个
                                    Log.d(TAG, " 有3门 班级 一样 1|2同步处理");
                                    doSyc(strClassId, CourseId.get(1), BigenCard.get(1), fixId, mCurrentTime, "1", "-1", "1", "0", "in");
                                    doSyc(strClassId, CourseId.get(2), BigenCard.get(2), fixId, mCurrentTime, "1", "-1", "1", "0", "in");
                                } else if (mets.size() == 2 && BigenCard.size() == 2) { //2个课程
                                    Log.d(TAG, "0-" + mets.get(0).getClassId() + "1" + mets.get(1).getClassId());
                                    if (mets.get(0).getClassId().equals(mets.get(1).getClassId())) {
                                        Log.d(TAG, "有2门 班级 一样 做同步处理 课程  1 ");
                                        doSyc(strClassId, CourseId.get(1), BigenCard.get(1), fixId, mCurrentTime, "1", "-1", "1", "0", "in");
                                    }
                                }
                            } else if (mSharePreferenceUtil.getIsSameClass() == 1 && me.getCheckMode() == 2) {//不同班级 && CheckMode2 半天
                                Log.d(TAG, "IsSameClass =1 不同班级 有可能有两个一样的班级出现");
                                if (mets.size() == 3 && BigenCard.size() == 3) {//先判断课程 最多3个
                                    if (mets.get(0).getClassId().equals(mets.get(1).getClassId())) { //
                                        Log.d(TAG, "不同班级 IsSameClass =1  课程 0 | 1 classId 相同");
                                        doSyc(strClassId, CourseId.get(1), BigenCard.get(1), fixId, mCurrentTime, "1", "-1", "1", "0", "in");
                                    }
                                    if (mets.get(0).getClassId().equals(mets.get(2).getClassId())) {
                                        Log.d(TAG, "不同班级 IsSameClass =1 一样  课程 0 | 2 classId 相同");
                                        doSyc(strClassId, CourseId.get(2), BigenCard.get(2), fixId, mCurrentTime, "1", "-1", "1", "0", "in");
                                    }
                                    if (mets.get(1).getClassId().equals(mets.get(2).getClassId())) {
                                        Log.d(TAG, "不同班级 IsSameClass =1 班级  课程 1 | 2 classId 相同");
                                        doSyc(strClassId, CourseId.get(2), BigenCard.get(2), fixId, mCurrentTime, "1", "-1", "1", "0", "in");

                                    }
                                }
                            }

                        }


                        break;
                    case "IN_late":

                        if (a != null) {

                            Log.d(TAG, "reList re IN_late" + a.toString());
                            Record re = new Record();
                            re.setId(a.getId());
                            re.setWlkh(a.getWlkh());
                            re.setClassId(a.getClassId());
                            re.setCourseId(a.getCourseId());
                            re.setTime(mCurrentTime);
                            re.setInResult("2");//签到状态(1-正常 2-迟到4-缺勤 )
                            re.setOutResult("-1");// //签退状态(1-正常  3-早退)
                            re.setAttendResult("2"); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退
                            re.setTermCode(a.getTermCode());//设备号
                            re.setLg("0");//签到签退标识0-签到，1-签退  -1 缺勤
                            re.setUserId(a.getUserId());
                            re.setIsUpload(a.getIsUpload());
                            re.setTag("in");
                            re.setSatrtTime(a.getSatrtTime());
                            re.setEndTime(a.getEndTime());

                            mRecordDao.update(re);
                            setAdapterUI(fixId, false);
                            Handler sHandler = new Handler();
                            sHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    q_dao_s.play(1, 1, 1, 0, 0, 1);
                                    Toast.makeText(ReMainActivity.this, "签到成功！", Toast.LENGTH_SHORT).show();
                                }
                            }, 500);
                            takePicture(fixId, a.getUserId());

                            //特殊情况 同班级 且 半天考勤  //1:有可能2门 班级 一样 做同步处理
                            if (mSharePreferenceUtil.getIsSameClass() == 0 && me.getCheckMode() == 2) {// IsSameClass =0同班级 && CheckMode2 半天
                                Log.d(TAG, "IsSameClass =0同班级");
                                if (mets.size() == 3 && BigenCard.size() == 3) {//先判断课程 最多3个
                                    Log.d(TAG, " 有3门 班级 一样 1|2同步处理");
                                    doSyc(strClassId, CourseId.get(1), BigenCard.get(1), fixId, mCurrentTime, "2", "-1", "2", "0", "in");
                                    doSyc(strClassId, CourseId.get(2), BigenCard.get(2), fixId, mCurrentTime, "2", "-1", "2", "0", "in");
                                } else if (mets.size() == 2 && BigenCard.size() == 2) { //2个课程
                                    Log.d(TAG, "0-" + mets.get(0).getClassId() + "1" + mets.get(1).getClassId());
                                    if (mets.get(0).getClassId().equals(mets.get(1).getClassId())) {
                                        Log.d(TAG, "有2门 班级 一样 做同步处理 课程  1 ");
                                        doSyc(strClassId, CourseId.get(1), BigenCard.get(1), fixId, mCurrentTime, "2", "-1", "2", "0", "in");
                                    }
                                }
                            } else if (mSharePreferenceUtil.getIsSameClass() == 1 && me.getCheckMode() == 2) {//不同班级 && CheckMode2 半天
                                Log.d(TAG, "IsSameClass =1 不同班级 有可能有两个一样的班级出现");
                                if (mets.size() == 3 && BigenCard.size() == 3) {//先判断课程 最多3个
                                    if (mets.get(0).getClassId().equals(mets.get(1).getClassId())) { //
                                        Log.d(TAG, "不同班级 IsSameClass =1  课程 0 | 1 classId 相同");
                                        doSyc(strClassId, CourseId.get(1), BigenCard.get(1), fixId, mCurrentTime, "2", "-1", "2", "0", "in");
                                    }
                                    if (mets.get(0).getClassId().equals(mets.get(2).getClassId())) {
                                        Log.d(TAG, "不同班级 IsSameClass =1 一样  课程 0 | 2 classId 相同");
                                        doSyc(strClassId, CourseId.get(2), BigenCard.get(2), fixId, mCurrentTime, "2", "-1", "2", "0", "in");
                                    }
                                    if (mets.get(1).getClassId().equals(mets.get(2).getClassId())) {
                                        Log.d(TAG, "不同班级 IsSameClass =1 班级  课程 1 | 2 classId 相同");
                                        doSyc(strClassId, CourseId.get(2), BigenCard.get(2), fixId, mCurrentTime, "2", "-1", "2", "0", "in");

                                    }
                                }
                            }
                        }

                        break;
                    case "IN_invalid":
                        soundPool1.play(1, 1, 1, 0, 0, 1);
                        break;
                }
            } else if (DatetimeUtil.TimeCompare(DatetimeUtil.getSysDate("HH:mm"), DatetimeUtil.gethour(End), DatetimeUtil.gethour(BigenOut)) && !isFlagTui) {//大于签到 小于签退时间内 记录迟到
                Log.d(TAG, "卡存在oooo大于签到 小于签退时间内 记录迟到");
                Record red = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(strClassId), RecordDao.Properties.CourseId.eq(strCourseUuid), RecordDao.Properties.Wlkh.eq(fixId), RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.Tag.eq("in")).unique();
                if (red != null) {
//                    soundPool_q_dao_f.play(1, 1, 1, 0, 0, 1);
                    q_ni_Already_dao.play(1, 1, 1, 0, 0, 1);
                    Toast.makeText(ReMainActivity.this, "您已签到！", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "已签到过了---");
                    Log.d(TAG, "在签到时段--doTimeSlotIn vreListE" + red.toString());
                    return;
                } else {
                    Log.d(TAG, "没有签到过---");

                }

                Record a = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(strClassId), RecordDao.Properties.CourseId.eq(strCourseUuid), RecordDao.Properties.Wlkh.eq(fixId), RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.Tag.eq("")).unique();

                if (a != null) {
                    Log.d(TAG, "卡存在oooo大于签到 小于签退时间内 记录迟到 a != null");
                } else {
                    q_ni_buzaibenban_q.play(1, 1, 1, 0, 0, 1);
                    Toast.makeText(ReMainActivity.this, "您不在本班上课！", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "卡不存在！！");
                    return;
                }


                if (a != null) {

                    Log.d(TAG, "reList re" + a.toString());
                    Record re = new Record();
                    re.setId(a.getId());
                    re.setWlkh(a.getWlkh());
                    re.setClassId(a.getClassId());
                    re.setCourseId(a.getCourseId());
                    re.setTime(mCurrentTime);
                    re.setInResult("2");//签到状态(1-正常 2-迟到4-缺勤 )
                    re.setOutResult("-1");// //签退状态(1-正常  3-早退)
                    re.setAttendResult("2"); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退
                    re.setTermCode(a.getTermCode());//设备号
                    re.setLg("0");//签到签退标识0-签到，1-签退  -1 缺勤
                    re.setUserId(a.getUserId());
                    re.setIsUpload(a.getIsUpload());
                    re.setTag("in");
                    re.setSatrtTime(a.getSatrtTime());
                    re.setEndTime(a.getEndTime());

                    mRecordDao.update(re);
                    setAdapterUI(fixId, false);
                    Handler sHandler = new Handler();
                    sHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            q_dao_late.play(1, 1, 1, 0, 0, 1);
                            Toast.makeText(ReMainActivity.this, "您来的太迟了！", Toast.LENGTH_SHORT).show();
                        }
                    }, 500);
                    takePicture(fixId, a.getUserId());

                    //特殊情况 同班级 且 半天考勤  //1:有可能2门 班级 一样 做同步处理
                    if (mSharePreferenceUtil.getIsSameClass() == 0 && me.getCheckMode() == 2) {// IsSameClass =0同班级 && CheckMode2 半天
                        Log.d(TAG, "IsSameClass =0同班级");
                        if (mets.size() == 3 && BigenCard.size() == 3) {//先判断课程 最多3个
                            Log.d(TAG, " 有3门 班级 一样 1|2同步处理");
                            doSyc(strClassId, CourseId.get(1), BigenCard.get(1), fixId, mCurrentTime, "2", "-1", "2", "0", "in");
                            doSyc(strClassId, CourseId.get(2), BigenCard.get(2), fixId, mCurrentTime, "2", "-1", "2", "0", "in");
                        } else if (mets.size() == 2 && BigenCard.size() == 2) { //2个课程
                            Log.d(TAG, "0-" + mets.get(0).getClassId() + "1" + mets.get(1).getClassId());
                            if (mets.get(0).getClassId().equals(mets.get(1).getClassId())) {
                                Log.d(TAG, "有2门 班级 一样 做同步处理 课程  1 ");
                                doSyc(strClassId, CourseId.get(1), BigenCard.get(1), fixId, mCurrentTime, "2", "-1", "2", "0", "in");
                            }
                        }
                    } else if (mSharePreferenceUtil.getIsSameClass() == 1 && me.getCheckMode() == 2) {//不同班级 && CheckMode2 半天
                        Log.d(TAG, "IsSameClass =1 不同班级 有可能有两个一样的班级出现");
                        if (mets.size() == 3 && BigenCard.size() == 3) {//先判断课程 最多3个
                            if (mets.get(0).getClassId().equals(mets.get(1).getClassId())) { //
                                Log.d(TAG, "不同班级 IsSameClass =1  课程 0 | 1 classId 相同");
                                doSyc(strClassId, CourseId.get(1), BigenCard.get(1), fixId, mCurrentTime, "2", "-1", "2", "0", "in");
                            }
                            if (mets.get(0).getClassId().equals(mets.get(2).getClassId())) {
                                Log.d(TAG, "不同班级 IsSameClass =1 一样  课程 0 | 2 classId 相同");
                                doSyc(strClassId, CourseId.get(2), BigenCard.get(2), fixId, mCurrentTime, "2", "-1", "2", "0", "in");
                            }
                            if (mets.get(1).getClassId().equals(mets.get(2).getClassId())) {
                                Log.d(TAG, "不同班级 IsSameClass =1 班级  课程 1 | 2 classId 相同");
                                doSyc(strClassId, CourseId.get(2), BigenCard.get(2), fixId, mCurrentTime, "2", "-1", "2", "0", "in");

                            }
                        }
                    }
                }

            } else if (false) {//开启签退，大于签退的 记录签退

            } else if (me.getNeedCheckout() == 1 && mResult != null && isFlagTui) {// 开启签退
                // 获取当前 list
                int mSize = mResult.getCourse().size();
                List<AttendanceResutl.CourseBean.ListBean> mList = new ArrayList<>();
                if (mList == null && mResult.getCourse().size() <= 0) {
                    Log.d(TAG, "无数据--");
                    return;
                }
                for (int i = 0; i < mSize; i++) {
                    AttendanceResutl.CourseBean cBean = mResult.getCourse().get(i);
                    if (strBigenTime.equals(cBean.getBeginTime())) {
                        List<AttendanceResutl.CourseBean.ListBean> list = cBean.getList();
                        mList.addAll(list);
                        break;
                    }
                }
                boolean isNotNull = false;
                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).getFactoryfixId().equals(fixId) && mList.get(i).getUseState() == 1) {
                        isNotNull = true;
                        break;
                    }
                }
                if (isNotNull) {//存在
                    Log.d(TAG, "签退 区域内-卡号 在 该数据内--fixId" + fixId);
                } else {//不存在
                    Log.d(TAG, "签退 区域内-卡号不在 该数据内--fixId" + fixId);
                    q_wu_ni_ke.play(1, 1, 1, 0, 0, 1);
                    Toast.makeText(ReMainActivity.this, "没有您的课程！", Toast.LENGTH_SHORT).show();
                    return;
                }


                Log.d(TAG, "签退 区域内---");
                Log.d(TAG, "OutBefore()=" + me.getOutBefore() + "OutLate()=" + me.getOutLate() + " mCurrentTime=" + mCurrentTime);


                String targetOut = isOutTimeRuleFunc(strEndTime, me.getOutBefore(), me.getOutLate(), me.getLeaveEarly(), "OUT_");//strEndTime, me.getOutBefore(), me.getOutLate(), me.getLeaveEarly()
                Log.d(TAG, "fun-targetOUT-" + targetOut);
                Record re = new Record();
                switch (targetOut) {
                    case "OUT_valid":
                        Record red = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(strClassId), RecordDao.Properties.CourseId.eq(strCourseUuid), RecordDao.Properties.Wlkh.eq(fixId), RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.Tag.eq("out")).unique();
                        if (red != null) {
                            if ("3".equals(red.getOutResult())) {//如果是早退，在正常签退 时间 还可以更新
                                re.setId(red.getId());
                                re.setWlkh(red.getWlkh());
                                re.setClassId(red.getClassId());
                                re.setCourseId(red.getCourseId());
                                re.setTime(mCurrentTime);
                                re.setInResult("1");//签到状态(1-正常 2-迟到4-缺勤 )
                                re.setOutResult("1");// //签退状态(1-正常  3-早退)
                                re.setAttendResult("1"); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退
                                re.setTermCode(red.getTermCode());//设备号
                                re.setLg("1");//签到签退标识0-签到，1-签退  -1 缺勤
                                re.setUserId(red.getUserId());
                                re.setIsUpload(false);
                                re.setTag("out");
                                re.setSatrtTime(red.getSatrtTime());
                                re.setEndTime(red.getEndTime());

                                mRecordDao.update(re);
                                Log.d(TAG, "已签早退 现更新 ---" + re.toString());
                                q_tui_s.play(1, 1, 1, 0, 0, 1);
                                Toast.makeText(ReMainActivity.this, "签退成功！", Toast.LENGTH_SHORT).show();
                                setAdapterUI(fixId, true);
                                return;
                            } else {
//                                soundPool_q_tui_s.play(1, 1, 1, 0, 0, 1);
                                q_ni_Already_tui.play(1, 1, 1, 0, 0, 1);
                                Toast.makeText(ReMainActivity.this, "您已签退！", Toast.LENGTH_SHORT).show();
                                Log.d(TAG, "已签 退---");
                                Log.d(TAG, "在签 退时段--");
                                return;
                            }
                        } else {
                            Log.d(TAG, "没有签 退 过---");

                        }

                        re.setId(null);
                        re.setWlkh(pe.getWlkh());
                        re.setClassId(pe.getClassId());
                        re.setCourseId(CourseId.get(indexBigen));
                        re.setTime(mCurrentTime);
                        re.setInResult("1");//签到状态(1-正常 2-迟到4-缺勤 )
                        re.setOutResult("1");// //签退状态(1-正常  3-早退)
                        re.setAttendResult("1"); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退
                        re.setTermCode(pe.getTermCode());//设备号
                        re.setLg("1");//签到签退标识0-签到，1-签退  -1 缺勤
                        re.setUserId(pe.getUserId());
                        re.setIsUpload(false);
                        re.setTag("out");
                        re.setSatrtTime(strBigenTime);
                        re.setEndTime(strEndTime);

                        mRecordDao.insert(re);

                        setAdapterUI(fixId, true);
                        Handler sHandler = new Handler();
                        sHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                q_tui_s.play(1, 1, 1, 0, 0, 1);
                                Toast.makeText(ReMainActivity.this, "签退成功！", Toast.LENGTH_SHORT).show();
                            }
                        }, 500);
                        takePicture(fixId, pe.getUserId());

                        //特殊情况 同班级 且 半天考勤  //1:有可能2门 班级 一样 做同步处理
                        if (mSharePreferenceUtil.getIsSameClass() == 0 && me.getCheckMode() == 2) {// 半天 IsSameClass() == 0 同班级
                            if (mets.size() == 3 && BigenCard.size() == 3 && CourseId.size() == 3) {//先判断课程 最多3个

                                Log.d(TAG, "签退 有3门 班级 一样 做同步处理");
                                pe = ps.get(1);
                                doSycOut(strClassId, CourseId.get(1), BigenCard.get(1), EndCard.get(1), fixId, mCurrentTime, pe, "1", "1", "1", "1", "out");

                                pe = ps.get(2);
                                doSycOut(mets.get(2).getClassId(), CourseId.get(2), BigenCard.get(2), EndCard.get(2), fixId, mCurrentTime, pe, "1", "1", "1", "1", "out");

                            } else if (mets.size() == 2 && BigenCard.size() == 2 && CourseId.size() == 2) { //2个课程
                                Log.d(TAG, "签退有 2门 班级 一样 做同步处理");
                                Log.d(TAG, "0-" + mets.get(0).getClassId() + "1" + mets.get(1).getClassId());
                                pe = ps.get(1);
                                doSycOut(strClassId, CourseId.get(1), BigenCard.get(1), EndCard.get(1), fixId, mCurrentTime, pe, "1", "1", "1", "1", "out");


                            }

                        } else if (mSharePreferenceUtil.getIsSameClass() == 1 && me.getCheckMode() == 2) {//不同班级 && CheckMode2 半天){
                            Log.d(TAG, "签退 同步 有3门IsSameClass() == 1  不同班级 同步处理111");
                            if (mets.size() == 3 && BigenCard.size() == 3 && CourseId.size() == 3) {//先判断课程 最多3个
                                if (mets.get(0).getClassId().equals(mets.get(1).getClassId())) { //
                                    Log.d(TAG, "签退 同步 0|1");
                                    pe = ps.get(1);
                                    doSycOut(strClassId, CourseId.get(1), BigenCard.get(1), EndCard.get(1), fixId, mCurrentTime, pe, "1", "1", "1", "1", "out");
                                }
                                if (mets.get(0).getClassId().equals(mets.get(2).getClassId())) {
                                    Log.d(TAG, "签退 同步 0|2");
                                    pe = ps.get(2);
                                    doSycOut(mets.get(2).getClassId(), CourseId.get(2), BigenCard.get(2), EndCard.get(2), fixId, mCurrentTime, pe, "1", "1", "1", "1", "out");

                                }
                                if (mets.get(1).getClassId().equals(mets.get(2).getClassId())) {
                                    Log.d(TAG, "签退 同步 1|2");
                                    pe = ps.get(2);
                                    doSycOut(mets.get(2).getClassId(), CourseId.get(2), BigenCard.get(2), EndCard.get(2), fixId, mCurrentTime, pe, "1", "1", "1", "1", "out");

                                }
                            }
                        }

                        Log.d(TAG, "签退正常---  ");
                        break;
                    case "OUT_late":
                        Record late = mRecordDao.queryBuilder().where(RecordDao.Properties.ClassId.eq(strClassId), RecordDao.Properties.CourseId.eq(strCourseUuid), RecordDao.Properties.Wlkh.eq(fixId), RecordDao.Properties.SatrtTime.eq(strBigenTime), RecordDao.Properties.Tag.eq("out")).unique();
                        if (late != null) {
                            q_ni_Already_tui.play(1, 1, 1, 0, 0, 1);
                            Toast.makeText(ReMainActivity.this, "您已签退！", Toast.LENGTH_SHORT).show();
                            Log.d(TAG, "已签 退---");
                            Log.d(TAG, "在签 退时段--");
                            return;
                        } else {
                            Log.d(TAG, "没有签 退 过---");

                        }

                        re.setId(null);
                        re.setWlkh(pe.getWlkh());
                        re.setClassId(pe.getClassId());
                        re.setCourseId(pe.getCourseId());
                        re.setTime(mCurrentTime);
                        re.setInResult("1");//签到状态(1-正常 2-迟到4-缺勤 )
                        re.setOutResult("3");// //签退状态(1-正常  3-早退)
                        re.setAttendResult("1"); //考勤结果1-正常 2-迟到 3-早退 4-缺勤 5-迟到早退
                        re.setTermCode(pe.getTermCode());//设备号
                        re.setLg("1");//签到签退标识0-签到，1-签退  -1 缺勤
                        re.setUserId(pe.getUserId());
                        re.setIsUpload(false);
                        re.setTag("out");
                        re.setSatrtTime(strBigenTime);
                        re.setEndTime(strEndTime);

                        mRecordDao.insert(re);
                        Log.d(TAG, "早退---  ");

                        setAdapterUI(fixId, true);
                        Handler sbeforeHandler = new Handler();
                        sbeforeHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                q_tui_s.play(1, 1, 1, 0, 0, 1);
                                Toast.makeText(ReMainActivity.this, "签退成功！", Toast.LENGTH_SHORT).show();
                            }
                        }, 500);
                        takePicture(fixId, pe.getUserId());

                        //特殊情况 同班级 且 半天考勤  //1:有可能2门 班级 一样 做同步处理
                        if (mSharePreferenceUtil.getIsSameClass() == 0 && me.getCheckMode() == 2) {// 半天 IsSameClass() == 0 同班级
                            if (mets.size() == 3 && BigenCard.size() == 3 && CourseId.size() == 3) {//先判断课程 最多3个

                                Log.d(TAG, "签退 有3门 班级 一样 做同步处理");
                                pe = ps.get(1);
                                doSycOut(strClassId, CourseId.get(1), BigenCard.get(1), EndCard.get(1), fixId, mCurrentTime, pe, "1", "3", "1", "1", "out");

                                pe = ps.get(2);
                                doSycOut(mets.get(2).getClassId(), CourseId.get(2), BigenCard.get(2), EndCard.get(2), fixId, mCurrentTime, pe, "1", "3", "1", "1", "out");

                            } else if (mets.size() == 2 && BigenCard.size() == 2 && CourseId.size() == 2) { //2个课程
                                Log.d(TAG, "签退有 2门 班级 一样 做同步处理");
                                Log.d(TAG, "0-" + mets.get(0).getClassId() + "1" + mets.get(1).getClassId());
                                pe = ps.get(1);
                                doSycOut(strClassId, CourseId.get(1), BigenCard.get(1), EndCard.get(1), fixId, mCurrentTime, pe, "1", "3", "1", "1", "out");


                            }

                        } else if (mSharePreferenceUtil.getIsSameClass() == 1 && me.getCheckMode() == 2) {//不同班级 && CheckMode2 半天){
                            Log.d(TAG, "签退 同步 有3门IsSameClass() == 1  不同班级 同步处理111");
                            if (mets.size() == 3 && BigenCard.size() == 3 && CourseId.size() == 3) {//先判断课程 最多3个
                                if (mets.get(0).getClassId().equals(mets.get(1).getClassId())) { //
                                    Log.d(TAG, "签退 同步 0|1");
                                    pe = ps.get(1);
                                    doSycOut(strClassId, CourseId.get(1), BigenCard.get(1), EndCard.get(1), fixId, mCurrentTime, pe, "1", "3", "1", "1", "out");
                                }
                                if (mets.get(0).getClassId().equals(mets.get(2).getClassId())) {
                                    Log.d(TAG, "签退 同步 0|2");
                                    pe = ps.get(2);
                                    doSycOut(mets.get(2).getClassId(), CourseId.get(2), BigenCard.get(2), EndCard.get(2), fixId, mCurrentTime, pe, "1", "3", "1", "1", "out");

                                }
                                if (mets.get(1).getClassId().equals(mets.get(2).getClassId())) {
                                    Log.d(TAG, "签退 同步 1|2");
                                    pe = ps.get(2);
                                    doSycOut(mets.get(2).getClassId(), CourseId.get(2), BigenCard.get(2), EndCard.get(2), fixId, mCurrentTime, pe, "1", "3", "1", "1", "out");

                                }
                            }
                        }
                        break;
                    case "OUT_invalid":
                        soundPool1.play(1, 1, 1, 0, 0, 1);
                        break;
                }

            } else {
                q_wu_ni_ke.play(1, 1, 1, 0, 0, 1);
                Toast.makeText(ReMainActivity.this, "无您的课程！", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "不在时区内---  ");
            }


        } else {
            q_wu_ni_ke.play(1, 1, 1, 0, 0, 1);
            Toast.makeText(ReMainActivity.this, "无您的课程！", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "不在时区内---  ");
        }

    }

    private void DispRecDataTest(ComBean ComRecData) {

      /*  StringBuilder sMsg = new StringBuilder();
        sMsg.append(ComRecData.sRecTime);
        sMsg.append("[");
        sMsg.append(ComRecData.sComPort);
        sMsg.append("]");
        sMsg.append("[Hex] ");*/
//        if (!isValid()) {
//            setRecvData(ComRecData.bRec);
//            //解析 TLV 格式数据
//
//            setValidDataFlag(true);
//        }


        Log.d("res", MyFunc.ByteArrToHex(ComRecData.bRec));
        // 10/17直接获取ID
        String resData = MyFunc.ByteArrToHex(ComRecData.bRec).trim();
        Log.d("res", "resData.length=" + resData.length());
        if (resData.endsWith("6B BB") && resData.length() >= 41) {
            Log.d("res", "10/17直接获取ID");
            String re = resData.substring(resData.length() - 20, resData.length() - 9);
            System.out.println(re);
            String[] rr = re.split(" ");
            String[] dd = new String[4];
            StringBuilder sb = new StringBuilder();
            dd[0] = rr[3];
            dd[1] = rr[2];
            dd[2] = rr[1];
            dd[3] = rr[0];
            for (int i = 0; i < dd.length; i++) {
                System.out.println(dd[i]);
                sb.append(dd[i]);
            }
            String factoryFixID = sb.toString();

            Log.d("res", "物理卡号：factoryFixID=" + factoryFixID + "cardId=" + cardId);
            if (!TextUtils.isEmpty(factoryFixID)) {
                Log.d("res", "刷卡成功");
                if (cardId.equals(factoryFixID)) {
                    Log.d("res", "连刷----");
                    startDowntime();
                    return;
                } else {
                    cardId = factoryFixID;
                    Log.d("res", "第一次刷----");
                }

            }















         /*   String strFix="2941840887";

            if(!TextUtils.isEmpty(strFix)){
                strFix=Long.toHexString(Long.valueOf(strFix));
            }
            if(strFix.equalsIgnoreCase(sb.toString())){
                Log.d("res","刷卡成功");
            }else{
                Log.d("res","刷卡失败");
            }*/


        } else {
            Log.d("res", "获取数据异常--");
        }


        //

        //测试
      /*  List<TLV> mlist= MyFunc.ByteArrToHexBB(ComRecData.bRec);

        String strFix="2941840887";

        if(!TextUtils.isEmpty(strFix)){
            strFix=Long.toHexString(Long.valueOf(strFix));
        }

        if(mlist!=null && mlist.size()>1){
            Log.d("res", mlist.get(1).value);
            if(strFix.equalsIgnoreCase(mlist.get(1).value)){
                Log.d("res","刷卡成功");
            }else{
                Log.d("res","刷卡失败");
            }
        }
        //
        sMsg.append(MyFunc.ByteArrToHex(ComRecData.bRec));


        sMsg.append("\r\n");
*/

    }

    /**
     * 生成拍照后图片的中间矩形的宽度和高度
     *
     * @param w 屏幕上的矩形宽度，单位px
     * @param h 屏幕上的矩形高度，单位px
     * @return
     */
    private Point createCenterPictureRect(int w, int h) {

        int wScreen = DisplayUtil.getScreenMetrics(this).x;
        int hScreen = DisplayUtil.getScreenMetrics(this).y;
        int wSavePicture = doGetPrictureSize().y; //因为图片旋转了，所以此处宽高换位
        int hSavePicture = doGetPrictureSize().x; //因为图片旋转了，所以此处宽高换位
        float wRate = (float) (wSavePicture) / (float) (wScreen);
        float hRate = (float) (hSavePicture) / (float) (hScreen);
        float rate = (wRate <= hRate) ? wRate : hRate;//也可以按照最小比率计算

        int wRectPicture = (int) (w * wRate);
        int hRectPicture = (int) (h * hRate);
        return new Point(wRectPicture, hRectPicture);

    }

    public Point doGetPrictureSize() {
        Camera.Size s = mCamera.getParameters().getPictureSize();
        return new Point(s.width, s.height);
    }

    public void initReGllery() {
        if (null == reGllery) {
            reGllery = new ReGallery_adapter(this, mListR);
            main_gallery.setAdapter(reGllery);
        }

    }

    public void initGallery_adapter() {
        if (null == gallery_adapter) {
            gallery_adapter = new Gallery_adapter(this, li);

        }
        if (null != mListR && null != reGllery) {
            mListR.clear();
            reGllery.notifyDataSetChanged();
        }

        gallery_adapter.notifyDataSetChanged();
        main_gallery.setAdapter(gallery_adapter);
    }

    private void GetMeetingInfo() {
        Api.getInstance().GetAttMeeting(new AbsAPICallback<AttMeetingResutl>(this) {
            @Override
            public void onNext(AttMeetingResutl attMeetingResutl) {
                if (attMeetingResutl.isCode()) {
                    if (null != attMeetingResutl.getMeeting()) {
                        if (attMeetingResutl.getMeeting().size() > 0) {
                            isDoChange = true;
                        }

                    }
                }
            }


        }, mSharePreferenceUtil.getEquipment(), getSysDate("yyyy-MM-dd HH:mm:ss"));


        //取现在时间
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.w("qqq", "--onResume()--");
        ThreadUtil.getInstance().submit(new Runnable() {
            @Override
            public void run() {
                loadMusic();
            }
        });

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.w("qqq", "--onPause()--");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.w("qqq", "--onStop()--");
        if (null != mDownTimer) {//问题：会议app手误退出后，再次打开考勤app，跳转会议app，刷卡出现双重语音
            mDownTimer.cancel();
            mDownTimer = null;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.w("qqq", "--onStart()--");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.w("qqq", "--onRestart()--");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.w("qqq", "--onRestoreInstanceState--");
    }

    /**
     * @author
     * @Description: 1：隐藏清除视图2:还原之前 默认照片
     * @Create Date:2017/12/7
     */
    private void doDisEnableView() {
        List<MeetingResutl> mlist = new ArrayList<>();
        setupViews(R.layout.layout_depar, R.layout.layout_department, R.id.layout_more, R.id.tiee, mlist, 0);
        practical.setText("0/0/0");
        listView.setVisibility(View.GONE);

        //清除网络历史图片资源
        if (null != li && null != gallery_adapter) {
            li.clear();
            gallery_adapter.clear();
        }
        if (mListR.size() > 0) {
            mListR.clear();
        }
        //加载本地资源
        mListR.add(1);
        mListR.add(2);
        mListR.add(3);
        reGllery = new ReGallery_adapter(this, mListR);
        main_gallery.setAdapter(reGllery);

    }

    /**
     * 获取缓存数据
     */
    private void getCacheData() {
        mResult = (AttendanceResutl) MyFileUtils.readFile2Object(MyFileUtils.mResultPath, AttendanceResutl.class);
        List<MeetingResutl> metsT = (List<MeetingResutl>) MyFileUtils.readFile2Object1(MyFileUtils.mets, new TypeToken<List<MeetingResutl>>() {
        }.getType());
        if (null == mets) {
            mets = new ArrayList<MeetingResutl>();
        }
        if (null != metsT) {
            mets.clear();
            mets.addAll(metsT);
        }
        List<PersonnelResutl> psT = (List<PersonnelResutl>) MyFileUtils.readFile2Object1(MyFileUtils.ps, new TypeToken<List<PersonnelResutl>>() {
        }.getType());
        if (null == ps) {
            ps = new ArrayList<PersonnelResutl>();
        }
        if (null != psT) {
            ps.clear();
            ps.addAll(psT);
        }
        List<String> CourseIdT = (List<String>) MyFileUtils.readFile2Object1(MyFileUtils.CourseId, new TypeToken<List<String>>() {
        }.getType());
        if (null == CourseId) {
            CourseId = new ArrayList<String>();
        }
        if (null != CourseIdT) {
            CourseId.clear();
            CourseId.addAll(CourseIdT);
        }
        List<String> BigenCardT = (List<String>) MyFileUtils.readFile2Object1(MyFileUtils.BigenCard, new TypeToken<List<String>>() {
        }.getType());
        if (null == BigenCard) {
            BigenCard = new ArrayList<String>();
        }
        if (null != BigenCardT) {
            BigenCard.clear();
            BigenCard.addAll(BigenCardT);
        }
        List<String> EndCardT = (List<String>) MyFileUtils.readFile2Object1(MyFileUtils.EndCard, new TypeToken<List<String>>() {
        }.getType());
        if (null == EndCard) {
            EndCard = new ArrayList<String>();
        }
        if (null != EndCardT) {
            EndCard.clear();
            EndCard.addAll(EndCardT);
        }

        List<String> class_attemdamceT = (List<String>) MyFileUtils.readFile2Object1(MyFileUtils.class_attemdamce, new TypeToken<List<String>>() {
        }.getType());
        if (null == class_attemdamce) {
            class_attemdamce = new ArrayList<String>();
        }
        if (null != class_attemdamceT) {
            class_attemdamce.clear();
            class_attemdamce.addAll(class_attemdamceT);
        }
    }
}
